<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/avatar.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/avatar.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/avatar.png">
  <link rel="mask-icon" href="/images/avatar.png" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"notes.maxwi.com","root":"/","scheme":"Mist","version":"7.8.0","exturl":false,"sidebar":{"position":"right","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":true,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":true,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="关于|准备本为内容来源于《CUDA by Example.An Introduction to General-Purpose GPU Programming》学习整理，网上中英文版都有，其源码以及本文测试源码在github。部分内容来源于CUDA官方文档http:&#x2F;&#x2F;docs.nvidia.com&#x2F;cuda以及其他网上相关资料，官方文档右上角的搜索不是非常好用，如果没有搜索到你所需要的关键字可以">
<meta property="og:type" content="article">
<meta property="og:title" content="CUDA学习笔记">
<meta property="og:url" content="http://notes.maxwi.com/2015/06/11/CUDA-study-notes/index.html">
<meta property="og:site_name" content="blueyi&#39;s notes">
<meta property="og:description" content="关于|准备本为内容来源于《CUDA by Example.An Introduction to General-Purpose GPU Programming》学习整理，网上中英文版都有，其源码以及本文测试源码在github。部分内容来源于CUDA官方文档http:&#x2F;&#x2F;docs.nvidia.com&#x2F;cuda以及其他网上相关资料，官方文档右上角的搜索不是非常好用，如果没有搜索到你所需要的关键字可以">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="http://notes.maxwi.com/2015/06/11/CUDA-study-notes/GPU.jpg">
<meta property="og:image" content="http://notes.maxwi.com/2015/06/11/CUDA-study-notes/tid.jpg">
<meta property="og:image" content="http://notes.maxwi.com/2015/06/11/CUDA-study-notes/threads_organization.jpg">
<meta property="og:image" content="http://notes.maxwi.com/2015/06/11/CUDA-study-notes/syncthreads.jpg">
<meta property="og:image" content="http://notes.maxwi.com/2015/06/11/CUDA-study-notes/cuda_memories.jpg">
<meta property="og:image" content="http://notes.maxwi.com/2015/06/11/CUDA-study-notes/cuda_memories_usage.jpg">
<meta property="article:published_time" content="2015-06-11T08:42:08.000Z">
<meta property="article:modified_time" content="2015-06-11T08:42:08.000Z">
<meta property="article:author" content="blueyi">
<meta property="article:tag" content="CUDA">
<meta property="article:tag" content="Notes">
<meta property="article:tag" content="Top">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://notes.maxwi.com/2015/06/11/CUDA-study-notes/GPU.jpg">

<link rel="canonical" href="http://notes.maxwi.com/2015/06/11/CUDA-study-notes/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'en'
  };
</script>

  <title>CUDA学习笔记 | blueyi's notes</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="blueyi's notes" type="application/atom+xml">
<link rel="alternate" href="/rss2.xml" title="blueyi's notes" type="application/rss+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">blueyi's notes</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Follow Excellence,Success will chase you!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>Categories</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>About</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>Search
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="Searching..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="en">
    <link itemprop="mainEntityOfPage" href="http://notes.maxwi.com/2015/06/11/CUDA-study-notes/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/default_avatar.jpg">
      <meta itemprop="name" content="blueyi">
      <meta itemprop="description" content="心怀善意，虛怀若谷！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="blueyi's notes">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          CUDA学习笔记
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2015-06-11 16:42:08" itemprop="dateCreated datePublished" datetime="2015-06-11T16:42:08+08:00">2015-06-11</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">In</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/CUDA/" itemprop="url" rel="index"><span itemprop="name">CUDA</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="Symbols count in article">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">Symbols count in article: </span>
              <span>36k</span>
            </span>
            <span class="post-meta-item" title="Reading time">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">Reading time &asymp;</span>
              <span>33 mins.</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="关于-准备"><a href="#关于-准备" class="headerlink" title="关于|准备"></a>关于|准备</h2><p>本为内容来源于《CUDA by Example.An Introduction to General-Purpose GPU Programming》学习整理，网上中英文版都有，其源码以及本文测试源码在<a target="_blank" rel="noopener" href="https://github.com/blueyi/cuda_example">github</a>。部分内容来源于CUDA官方文档<a target="_blank" rel="noopener" href="http://docs.nvidia.com/cuda">http://docs.nvidia.com/cuda</a>以及其他网上相关资料，官方文档右上角的搜索不是非常好用，如果没有搜索到你所需要的关键字可以定位到所需文档后试试<code>ctrl+f</code>,例如<code>dim3</code>的概念。这里是一个中文版本的<a target="_blank" rel="noopener" href="http://www.nvidia.cn/docs/IO/57399/NVIDIA_CUDA_Programming_Guide_2.0Final.pdf">NVIDIA_CUDA_Programming_Guide_2.0Final</a>。<br><strong>新人入坑看这里，系统学习强烈推荐直接看官方这份编程指南：<a target="_blank" rel="noopener" href="http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html">http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html</a>，本文后期补充的大量内容都来自该指南。</strong><br><strong>看完指南再看官方的进阶文档，最佳实践指南：<a target="_blank" rel="noopener" href="http://docs.nvidia.com/cuda/cuda-c-best-practices-guide/">http://docs.nvidia.com/cuda/cuda-c-best-practices-guide/</a>，这些看完你也就完全入门了，并且跟上了CUDA的最新技术发展。</strong></p>
<span id="more"></span>

<p>书上使用的是C语言，为了顺便练习下C++且本文主要是为了以后自己查询所用，所以可能会有混用<code>C/C++</code>的情况，如果你不慎看到本文且发现了有问题的地方请及时与我联系，在以后的学习过程中我也会逐渐更正。</p>
<p><strong>特别推荐偶然间在网上找到的纽约大学的<code>CUDA</code>课程，地址在<a target="_blank" rel="noopener" href="http://cs.nyu.edu/courses/spring12/CSCI-GA.3033-012/">Graphics Processing Units (GPUs): Architecture and Programming</a>。该页面底部也推荐了一些其他非常好的GPU相关的编程网站。</strong></p>
<p>本文没有介绍Windows下环境安装等相关的内容，因为<code>NVIDIA</code>基本上干好了一切，这应该就是商业公司的好处。<a target="_blank" rel="noopener" href="https://developer.nvidia.com/cuda-zone">CUDA ZONE</a>上你可以找到所有<code>CUDA</code>环境及官方相关资料。<code>windows</code>下直接下载官方<code>CUDA Toolkit</code>安装即可，<code>Linux</code>下建议安装配置好<code>Nvida</code>显卡驱动且确定驱动正常运行后直接下载官方对应二进制包安装即可，这里建议安装个<code>snapper</code>并在你不确定是否能够完美配置好环境的情况下创建个快照，方便回滚。如果只是学习简单实例，且开发的文件较少并且熟悉<code>vim</code>,可以考虑使用<code>nvcc+vim</code>，不需要启动庞大的<code>VS</code>，当然<code>VS</code>也足够好用。以下是我用的<code>vim</code>针对<code>CUDA</code>的绑定，<code>Ctrl + F8</code>或<code>F8</code>一键编译并运行，其中<code>Ctrl + F8</code>会默认将CUDA官方示例中的头文件加入编译时的头文件查找路径中，方便编译官方示例，如果不是编译官方示例，直接使用<code>F8</code>即可。添加<code>--ptxas-options=-v</code>编译选项是为了在编译时输出核函数所使用的<code>register</code>和<code>shared memory</code>，方便自己根据需要调整block尺寸。</p>
<p>Linux下双显卡配置，可以参见：<a href="http://notes.maxwi.com/2017/02/26/ubuntu-cuda8-env-set/">http://notes.maxwi.com/2017/02/26/ubuntu-cuda8-env-set/</a></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;-- For CUDA development setting --</span></span><br><span class="line"><span class="string">&quot;</span> Ctrl + F8 compile, <span class="built_in">link</span> and execute .cu file with Samples header file</span><br><span class="line">map &lt;C-F8&gt; :call Nvcc_S() &lt;CR&gt;</span><br><span class="line">imap &lt;C-F8&gt; &lt;ESC&gt; :call Nvcc_S() &lt;CR&gt;</span><br><span class="line"><span class="string">&quot; F8 compile, link and execute .cu file without Samples header file</span></span><br><span class="line"><span class="string">map &lt;F8&gt; :call Nvcc() &lt;CR&gt;</span></span><br><span class="line"><span class="string">imap &lt;F8&gt; &lt;ESC&gt; :call Nvcc() &lt;CR&gt;</span></span><br><span class="line"><span class="string">&quot;</span>将CUDA Samples中的头文件加入编译路径</span><br><span class="line">func! Nvcc_S()</span><br><span class="line">    exe <span class="string">&quot;:ccl&quot;</span></span><br><span class="line">    exe <span class="string">&quot;:update&quot;</span></span><br><span class="line">    <span class="keyword">if</span> g:iswindows</span><br><span class="line">        exe <span class="string">&#x27;:!nvcc --ptxas-options=-v % -I &quot;C:\ProgramData\NVIDIA Corporation\CUDA Samples\v7.5\common\inc&quot; -o %&lt;.exe&#x27;</span></span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        exe <span class="string">&#x27;:!nvcc --ptxas-options=-v % -I &quot;/usr/local/cuda-8.0/samples/common/inc&quot; -o %&lt;.o&#x27;</span></span><br><span class="line">    endif</span><br><span class="line">    <span class="keyword">if</span> v:shell_error == 0</span><br><span class="line">        <span class="keyword">if</span> g:iswindows</span><br><span class="line">            exe <span class="string">&quot;:!%&lt;.exe&quot;</span></span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">            exe <span class="string">&quot;:!./%&lt;.o&quot;</span></span><br><span class="line">        endif</span><br><span class="line">    endif</span><br><span class="line">endfunc</span><br><span class="line"></span><br><span class="line">func! Nvcc()</span><br><span class="line">    exe <span class="string">&quot;:ccl&quot;</span></span><br><span class="line">    exe <span class="string">&quot;:update&quot;</span></span><br><span class="line">    <span class="keyword">if</span> g:iswindows</span><br><span class="line">        exe <span class="string">&#x27;:!nvcc --ptxas-options=-v % -o %&lt;.exe&#x27;</span></span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        exe <span class="string">&#x27;:!nvcc --ptxas-options=-v % -o %&lt;.o&#x27;</span></span><br><span class="line">    endif</span><br><span class="line">    <span class="keyword">if</span> v:shell_error == 0</span><br><span class="line">        <span class="keyword">if</span> g:iswindows</span><br><span class="line">            exe <span class="string">&quot;:!%&lt;.exe&quot;</span></span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">            exe <span class="string">&quot;:!./%&lt;.o&quot;</span></span><br><span class="line">        endif</span><br><span class="line">    endif</span><br><span class="line">endfunc</span><br></pre></td></tr></table></figure>

<h2 id="CUDA-C-简介及基本概念"><a href="#CUDA-C-简介及基本概念" class="headerlink" title="CUDA C++简介及基本概念"></a>CUDA C++简介及基本概念</h2><p><img data-src="GPU.jpg" alt="GPU结构概览"><br>硬件层面上CUDA架构中的GPU计算单元由很多的SM（Stream Multiprocess）组成，而每个SM又由多个CUDA Core（对应于single process）组成。这跟CUDA编程中的线程（thread）、线程块（block）、线程格（grid）并无直接的一一对应关系，CUDA编程中为了便于线程的调度和管理采用多维的方式来组织线程。</p>
<p>2.1 CPU中执行的代码称为主机代码，GPU中执行的代码称为设备代码,在GPU设备上执行的函数通常称为核函数（kernel）。一个程序中可以包含多个核函数。</p>
<p>2.2 通过<code>__global__ type func()</code>来声明可以从主机上调用并在设备上运行的代码，通过<code>__device__ type func()</code>来声明只能从其他<code>__device__</code>函数或者从<code>__global__</code>函数调用而需要在设备上执行的代码，也就是说其声明的函数只能在GPU上调用。<code>CUDA</code>中的并行化即是指这个核函数在程序启动后可以由多个线程同时来执行这个核函数一次。</p>
<p>2.3 通过<code>func&lt;&lt;&lt;N,1&gt;&gt;&gt;()</code>来调用需要在GPU中执行的代码。其中参数N表示设备在执行该函数时使用的并行线程块数量，参数1表示<code>CUDA</code>运行时在每个线程块中创建的线程数量。</p>
<p>2.4 GPU的大致使用流程总结如下：</p>
<ul>
<li>1.使用关键定<code>__global__</code>声明核函数，eg: <code>__global__ void kernel(int a, int b, int *c);</code></li>
<li>2.定义需要在GPU中使用的所有数据指针，eg: <code>int *dev_a;</code></li>
<li>3.然后通过<code>cudaMalloc</code>为所有需要设备内存的数据指针分配设备内存，注意<code>cudaMalloc()</code>分配的是<code>global memory</code>,也就是全局内存。eg: <code>cudaMalloc((void**)&amp;dev_a, sizeof(int));</code></li>
<li>4.通过<code>cudaMemcpy</code>将GPU代码中需要使用到的主机数据复制到GPU，eg: <code>cudaMemcpy(dev_b, b, N*sizeof(b), cudaMemcpyHostToDevice);</code></li>
<li>5.调用GPU核函数，eg: <code>kernel&lt;&lt;&lt;1,1&gt;&gt;&gt;(1, 2, dev_b);</code></li>
<li>6.调用后将需要在主机中使用的数据通过<code>cudaMemcpy</code>从设备内存复制到主机内存中使用，eg: <code>cudaMemcpy(b, dev_b,sizeof(int), cudaMemcpyDeviceToHost);</code></li>
<li>7.最后调用<code>cudaFree</code>释放在GPU中分配的内存，eg: <code>cudaFree(dev_a);</code></li>
</ul>
<p>举例如下：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="function">__global__ <span class="type">void</span> <span class="title">add</span><span class="params">(<span class="type">int</span> a, <span class="type">int</span> *b, <span class="type">int</span> *c)</span> <span class="comment">//声明需要在GPU中执行的核函数</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	*c = a + *b;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">(<span class="type">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="type">int</span> b, c;</span><br><span class="line">	b = <span class="number">3</span>;</span><br><span class="line">	<span class="type">int</span> *dev_b, *dev_c; <span class="comment">//声明GPU需要使用到的指针</span></span><br><span class="line">	<span class="built_in">cudaMalloc</span>((<span class="type">void</span> **)&amp;dev_b, <span class="built_in">sizeof</span>(<span class="type">int</span>)); <span class="comment">//在GPU内存中为dev_b分配内存</span></span><br><span class="line">	<span class="built_in">cudaMalloc</span>((<span class="type">void</span> **)&amp;dev_c, <span class="built_in">sizeof</span>(<span class="type">int</span>)); <span class="comment">//在GPU内存中为dev_c分配内存</span></span><br><span class="line">	<span class="built_in">cudaMemcpy</span>(dev_b, &amp;b, <span class="built_in">sizeof</span>(<span class="type">int</span>), cudaMemcpyHostToDevice); <span class="comment">//将核函数需要的数据复制到设备内存</span></span><br><span class="line">	add&lt;&lt;&lt;<span class="number">1</span>,<span class="number">1</span>&gt;&gt;&gt;(<span class="number">2</span>, dev_b, dev_c); <span class="comment">//调用核函数</span></span><br><span class="line">	<span class="built_in">cudaMemcpy</span>(&amp;c, dev_c, <span class="built_in">sizeof</span>(<span class="type">int</span>), cudaMemcpyDeviceToHost); <span class="comment">//将计算结果dev_c中的数据从设备内存复制到主机内存</span></span><br><span class="line">	std::cout &lt;&lt; <span class="number">2</span> &lt;&lt; <span class="string">&quot; + &quot;</span> &lt;&lt; b &lt;&lt; <span class="string">&quot; = &quot;</span> &lt;&lt; c &lt;&lt; std::endl;</span><br><span class="line">	<span class="built_in">cudaFree</span>(dev_b); <span class="comment">//释放设备内存</span></span><br><span class="line">	<span class="built_in">cudaFree</span>(dev_c);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>这里特别强调，如果你发现本文中带有中文注释的示例无法通过编译，请手动设置源代码文件格式为<code>utf-8 with bomb</code>, <code>vim</code>设置方法为<code>:set bomb</code>,查看当前文件是否带<code>bomb</code>用<code>:set bomb?</code>,<code>EmEditor</code>另存时选择<code>UTF-8 with signature</code>,其他编辑器类似。当然VS通常默认应该是带<code>bomb</code>，否则请认真检查。这个问题花了我一下午尝试，怀疑是<code>nvcc</code>的兼容问题或者BUG，因为在<code>linux</code>下无论是带不带bomb，都能正常编译，但在windows下如果带有中文注释必须带bomb，或者将每一行带中文注释的行前后各放置一个空行。</strong></p>
<p>2.5 <code>cudaDeviceProp</code>结构体中包含了当前<code>CUDA</code>设备的几乎所有属性，可以通过<code>cudaGetDeviceCount(&amp;count)</code>查询当前计算机中<code>CUDA</code>设备数量，使用<code>cudaGetDevice(&amp;dev)</code>获取当前使用的设备ID，设备ID从0开始编号。使用<code>cudaGetDeviceProperties(&amp;prop, i)</code>函数来获取ID为i的<code>CUDA</code>设备的属性。使用<code>cudaChooseDevice(&amp;dev, &amp;prop)</code>可以获取符合<code>prop</code>要求的设备ID到<code>dev</code>，使用<code>cudaSetDevice(dev)</code>可以设置使用ID为dev的对应设备。有关设备属性的具体内容及用法参见<a target="_blank" rel="noopener" href="http://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__DEVICE.html#group__CUDART__DEVICE_1gf61f9ae0fe2d93b5b968756684a49460">http://docs.nvidia.com/cuda</a>。<br><strong>补充：可以使用NVIDIA官方Toolkit自带的工具<code>nvidia-smi</code>来查询GPU信息，功能强大,该工具默认安装路径为<code>C:\Program Files\NVIDIA Corporation\NVSMI\nvidia-smi.exe</code>，详情查看官方DOC。也可以在通过指定环境变量<code>CUDA_VISIBLE_DEVICES</code>来设置对于系统程序CUDA设备的可见性</strong></p>
<p>2.6 设备指针使用限制：</p>
<ul>
<li>可以将<code>cudaMalloc()</code>分配的指针传递给在设备上执行的函数。</li>
<li>可以在设备代码中使用<code>cudaMalloc()</code>分配的指针进行内存读/写操作。</li>
<li>可以将<code>cudaMalloc()</code>分配的指针传递给在主机上执行的函数。</li>
<li>不能在主机代码中使用<code>cudaMalloc()</code>分配的指针进行内存读/写操作。</li>
<li>总之，主机代码只能访问主机内存，设备代码只能访问设备内存。</li>
</ul>
<h2 id="CUDA-C并行编程的一维线程管理"><a href="#CUDA-C并行编程的一维线程管理" class="headerlink" title="CUDA C并行编程的一维线程管理"></a>CUDA C并行编程的一维线程管理</h2><p>3.1 <code>CUDA</code>使用线程格管理线程，线程格可以是一维的线程块集合，也可以是二维的线程块集合。核函数的每个副本都可以通过内置变量<code>blockIdx</code>来判断哪个线程块正在执行它，即确定线程块的索引。也可以通过<code>gridDim</code>来获得线程格中所包含的线程块的数量,通过<code>blockDim</code>可以获得线程块中所包含的线程的数量。<br>对于一个一维的线程格来说，不需要特别定义，可以直接使用<code>blockIdx.x</code>来获取当前线程块的索引，此时对应的核函数调用为<code>kernel&lt;&lt;&lt;N, 1&gt;&gt;&gt;();</code>即启动N个线程块；或者使用<code>threadIdx.x</code>来获取当前线程块中线程的索引，此时对应的核函数调用为<code>kernel&lt;&lt;&lt;1, N&gt;&gt;&gt;();</code>即启动一个线程块，该线程块启动N个线程。</p>
<p>3.2 GPU利用一维线程格进行矢量求和的例子:<br>所有的<code>tid</code>都是为了确定输入数组中的一个全局偏移，用于确定当前执行该核函数的线程应该计算数组中哪个元素的值,所以它必须要包含在它之前所有线程的索引值。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">const</span> <span class="type">int</span> N = <span class="number">10000</span>;</span><br><span class="line"></span><br><span class="line"><span class="function">__global__ <span class="type">void</span> <span class="title">add</span><span class="params">(<span class="type">int</span> *a, <span class="type">int</span> *b, <span class="type">int</span> *c)</span>	<span class="comment">//定义GPU函数</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">int</span> tid = blockIdx.x;			<span class="comment">//计算该线程块的索引值</span></span><br><span class="line"><span class="comment">//  int tid = threadIdx.x;			//计算该线程的索引处值</span></span><br><span class="line">    <span class="keyword">if</span> (tid &lt; N)  <span class="comment">//与并行线程块数N对应,此处通过if防止由于执行的线程数量超过N个时内存访问越界</span></span><br><span class="line">        c[tid] = a[tid] + b[tid];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">(<span class="type">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">int</span> a[N], b[N], c[N];			<span class="comment">//在堆上分配主机数据空间</span></span><br><span class="line">    <span class="type">int</span> *dev_a, *dev_b, *dev_c;			<span class="comment">//设备内存指针</span></span><br><span class="line">    <span class="built_in">cudaMalloc</span>((<span class="type">void</span>**)&amp;dev_a, N*<span class="built_in">sizeof</span>(<span class="type">int</span>));	<span class="comment">//在GPU上为数据分配设备内存</span></span><br><span class="line">    <span class="built_in">cudaMalloc</span>((<span class="type">void</span>**)&amp;dev_b, N*<span class="built_in">sizeof</span>(<span class="type">int</span>));</span><br><span class="line">    <span class="built_in">cudaMalloc</span>((<span class="type">void</span>**)&amp;dev_c, N*<span class="built_in">sizeof</span>(<span class="type">int</span>));</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; N; i++)			<span class="comment">//在cpu上为数组赋值，可参照设备代码add修改为GPU上的代码</span></span><br><span class="line">    &#123;</span><br><span class="line">        a[i] = -i;</span><br><span class="line">	b[i] = i * i;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">cudaMemcpy</span>(dev_a, a, N*<span class="built_in">sizeof</span>(<span class="type">int</span>), cudaMemcpyHostToDevice);   <span class="comment">//将主机上的数组复制到GPU内存中</span></span><br><span class="line">    <span class="built_in">cudaMemcpy</span>(dev_b, b, N*<span class="built_in">sizeof</span>(<span class="type">int</span>), cudaMemcpyHostToDevice);</span><br><span class="line"></span><br><span class="line">    add&lt;&lt;&lt;N, <span class="number">1</span>&gt;&gt;&gt;(dev_a, dev_b, dev_c);		<span class="comment">//调用设备函数,将启动N个线程块</span></span><br><span class="line"><span class="comment">//  add&lt;&lt;&lt;1, N&gt;&gt;&gt;(dev_a, dev_b, dev_c);		//调用设备函数,只启动一个线程块，该线程块将启动N个线程</span></span><br><span class="line"></span><br><span class="line">    <span class="built_in">cudaMemcpy</span>(c, dev_c, N*<span class="built_in">sizeof</span>(<span class="type">int</span>), cudaMemcpyDeviceToHost);   <span class="comment">//将计算后的GPU内存中的数据复制到主机内存，以便主机代码访问</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; N; i++)</span><br><span class="line">	std::cout &lt;&lt; i &lt;&lt; <span class="string">&quot;: &quot;</span> &lt;&lt; a[i] &lt;&lt; <span class="string">&quot; + &quot;</span> &lt;&lt; b[i] &lt;&lt; <span class="string">&quot; = &quot;</span> &lt;&lt; c[i] &lt;&lt; std::endl;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">cudaFree</span>(dev_a);    <span class="comment">//释放GPU内存</span></span><br><span class="line">    <span class="built_in">cudaFree</span>(dev_b);</span><br><span class="line">    <span class="built_in">cudaFree</span>(dev_c);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="线程协作-共享内存"><a href="#线程协作-共享内存" class="headerlink" title="线程协作|共享内存"></a>线程协作|共享内存</h2><p>4.1 硬件对线程块数量及线程块中包含的线程数量都有限制，具体限制可以通过CUDA API内置的结构体设备属性<code>cudaDeviceProp</code>查询。</p>
<p>4.2 线程格表示当前运行的线程块集合，线程格可以是二维，对应的内置变量<code>gridDim.x</code>中保存了线程格中每一维中的线程块数量；线程块表示当前运行的线程集合，线程块可以是三维的，对应的<code>blockDim.x</code>中保存了当前运行的线程块中每一维的线程数量。</p>
<p>4.3 当需要多个线程块并且每个线程块又包含多个线程时，索引计算方法为：<code>int tid = threadIdx.x + blockIdx.x * blockDim.x;</code>，其中索引tid相当于一个以线程块为行，线程为列的二维集合中某格所在的索引值。所以<code>threadIdx.x</code>表示当前线程所在线程块中某行的索引，<code>blockIdx.x</code>表示线程块索引，<code>blockDim.x</code>表示每个线程块中的线程数量。<code>gridDim.x</code>表示当前线程格中线程块的数量，线程格其实就是当前正在运行的线程块集合。如下图所示:<br><img data-src="tid.jpg" alt="一维线程格中线程索引对应关系"></p>
<p><img data-src="threads_organization.jpg" alt="CUDA线程组织形式"></p>
<p>4.4 在确定启动线程块的数量时记得考虑避免出现启动0个线程块的情况。例如若要每个线程块启动128个线程，假如我们总共需要启动N个并行线程，那么对应的线程块数量应为<code>N/128</code>。这样将导致当<code>N &lt; 128</code>时我们启动的线程块数量将为0，所以应该修改线程块数量为<code>(N+127)/128</code>，即计算大于或等于N的128的最小整数倍，同时不需要调用<code>ceil()</code>函数。</p>
<p>4.5 由于<code>gridDim.x</code>中存放了当前线程格中线程块的数量，<code>blockDim.x</code>中存放了当前线程块中线程的数量，所以<code>blockDim.x * gridDim.x</code>表示线程格中正在运行的线程块总数。</p>
<p>4.6 举例说明同时启动多个线程块及多个线程计算上述矢量求和的例子：<br>此处只给出核函数并说明函数调用。 </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">const</span> <span class="type">int</span> N = <span class="number">10000</span>;</span><br><span class="line"><span class="comment">/*N可以设置为任意编译器以及GPU内存限制下可以支持的数字，</span></span><br><span class="line"><span class="comment">因为我们可以限制线程和线程块数量，而让每个线程进行多次迭代*/</span></span><br><span class="line"><span class="comment">//核函数</span></span><br><span class="line"><span class="function">__global__ <span class="type">void</span> <span class="title">add</span><span class="params">(<span class="type">int</span> *a, <span class="type">int</span> *b, <span class="type">int</span> *c)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">int</span> tid = threadIdx.x + blockIdx.x * blockDim.x;  <span class="comment">//当前线程中线程的起始索引</span></span><br><span class="line">    <span class="keyword">while</span> (tid &lt; N)  <span class="comment">//使用一个线程进行多次计算</span></span><br><span class="line">    &#123;</span><br><span class="line">	c[tid] = a[tid] + b[tid];</span><br><span class="line">	tid += blockDim.x * gridDim.x;  </span><br><span class="line"><span class="comment">/*计算完成一次之后需要递增的步长为当前线程格中正在运行的线程数量。</span></span><br><span class="line"><span class="comment">因为每个线程的起始索引都如上所示，即至少以一个线程块中的线程数量为单位递增，</span></span><br><span class="line"><span class="comment">所以当前在运行的总的线程数量应为每个线程块中包含的线程总数乘以线程格中的线程块总数。*/</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//核函数调用</span></span><br><span class="line">add&lt;&lt;&lt;<span class="number">128</span>, <span class="number">128</span>&gt;&gt;&gt;(dev_a, dev_b, dev_c); <span class="comment">//线程块和线程的数量可以设置为硬件限制内的任何数值。</span></span><br></pre></td></tr></table></figure>

<p>4.7 使用数据类型<code>dim3</code>可以定义多维block以及thread。例如可以定义一个N<em>N的二维线程块，每个线程块中含有M</em>M的线程，方法为  </p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">dim3 block(N, N);  //默认第三维为1</span><br><span class="line">dim3 thread(M, M);</span><br><span class="line">kernel&lt;&lt;&lt;block, thread&gt;&gt;&gt;(type args);</span><br></pre></td></tr></table></figure>
<p>针对上面的普通数组加法的程序，可以修改核函数为  </p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">__global__ void add(int *a, int *b, int *c)</span><br><span class="line">&#123;</span><br><span class="line">   int x = threadIdx.x + blockIdx.x * blockDim.x;</span><br><span class="line">   int y = threadIdx.y + blockIdx.y * blockDim.y;</span><br><span class="line">   int tid = x + y * blockDim.x * gridDim.x;</span><br><span class="line">   while (tid &lt; N)</span><br><span class="line">   &#123;</span><br><span class="line">      c[tid] = a[tid] + b[tid];</span><br><span class="line">      tid += blockDim.x * gridDim.x * blockDim.y * gridDim.y;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>4.8 以下为书上的一个实现1024x1024大小波纹动画效果的代码，将每个线程对应于一个像素，具体内容见注释。  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;cuda.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;book.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;cpu_anim.h&quot;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">const</span> <span class="type">int</span> DIM = <span class="number">1024</span>; <span class="comment">//定义像素大小</span></span><br><span class="line"></span><br><span class="line"><span class="function">__global__ <span class="type">void</span> <span class="title">kernel</span><span class="params">( <span class="type">unsigned</span> <span class="type">char</span> *ptr, <span class="type">int</span> ticks )</span> </span>&#123;</span><br><span class="line">    <span class="comment">// map from threadIdx/BlockIdx to pixel position</span></span><br><span class="line">    <span class="type">int</span> x = threadIdx.x + blockIdx.x * blockDim.x;    </span><br><span class="line"><span class="comment">/*当前线程所在x轴坐标位置,注意每一个像素对应一个线程，如果定义每一个线程块包含16x16大小的</span></span><br><span class="line"><span class="comment">    线程数组，那么一共就需要DIM/16 x DIM/16个线程块。*/</span></span><br><span class="line">    <span class="type">int</span> y = threadIdx.y + blockIdx.y * blockDim.y;</span><br><span class="line">    <span class="type">int</span> offset = x + y * blockDim.x * gridDim.x;      </span><br><span class="line"><span class="comment">/*偏移量的计算与上图&quot;线程索引对应关系&quot;的计算方式一样。</span></span><br><span class="line"><span class="comment">只是此处偏移量是指位图的每个像素且每一个单元格对应一个线程块。*/</span></span><br><span class="line">    <span class="comment">// now calculate the value at that position</span></span><br><span class="line">    <span class="type">float</span> fx = x - DIM/<span class="number">2</span>;</span><br><span class="line">    <span class="type">float</span> fy = y - DIM/<span class="number">2</span>;</span><br><span class="line">    <span class="type">float</span> d = <span class="built_in">sqrtf</span>( fx * fx + fy * fy );</span><br><span class="line">    <span class="type">unsigned</span> <span class="type">char</span> grey = (<span class="type">unsigned</span> <span class="type">char</span>)(<span class="number">128.0f</span> + <span class="number">127.0f</span> * <span class="built_in">cos</span>(d/<span class="number">10.0f</span> - ticks/<span class="number">7.0f</span>)/(d/<span class="number">10.0f</span> + <span class="number">1.0f</span>));    </span><br><span class="line">    ptr[offset*<span class="number">4</span> + <span class="number">0</span>] = grey;</span><br><span class="line">    ptr[offset*<span class="number">4</span> + <span class="number">1</span>] = grey;</span><br><span class="line">    ptr[offset*<span class="number">4</span> + <span class="number">2</span>] = grey;</span><br><span class="line">    ptr[offset*<span class="number">4</span> + <span class="number">3</span>] = <span class="number">255</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">struct</span> <span class="title class_">DataBlock</span> &#123;</span><br><span class="line">    <span class="type">unsigned</span> <span class="type">char</span>   *dev_bitmap;</span><br><span class="line">    CPUAnimBitmap  *bitmap;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">generate_frame</span><span class="params">( DataBlock *d, <span class="type">int</span> ticks )</span> </span>&#123;</span><br><span class="line">    <span class="function">dim3    <span class="title">blocks</span><span class="params">(DIM/<span class="number">16</span>,DIM/<span class="number">16</span>)</span></span>;    <span class="comment">//定义一个二维线程块，默认第三维为1，关于dim3类型参见官网DOC。</span></span><br><span class="line">    <span class="function">dim3    <span class="title">threads</span><span class="params">(<span class="number">16</span>,<span class="number">16</span>)</span></span>;           <span class="comment">//定义每个线程块中包含的线程数为16x16。</span></span><br><span class="line">    kernel&lt;&lt;&lt;blocks,threads&gt;&gt;&gt;( d-&gt;dev_bitmap, ticks );</span><br><span class="line"></span><br><span class="line">    <span class="built_in">HANDLE_ERROR</span>( <span class="built_in">cudaMemcpy</span>( d-&gt;bitmap-&gt;<span class="built_in">get_ptr</span>(), d-&gt;dev_bitmap, d-&gt;bitmap-&gt;<span class="built_in">image_size</span>(), cudaMemcpyDeviceToHost ) );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// clean up memory allocated on the GPU</span></span><br><span class="line"><span class="function"><span class="type">void</span> <span class="title">cleanup</span><span class="params">( DataBlock *d )</span> </span>&#123;</span><br><span class="line">    <span class="built_in">HANDLE_ERROR</span>( <span class="built_in">cudaFree</span>( d-&gt;dev_bitmap ) ); </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">( <span class="type">void</span> )</span> </span>&#123;</span><br><span class="line">    DataBlock   data;</span><br><span class="line">    <span class="function">CPUAnimBitmap  <span class="title">bitmap</span><span class="params">( DIM, DIM, &amp;data )</span></span>;</span><br><span class="line">    data.bitmap = &amp;bitmap;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">HANDLE_ERROR</span>( <span class="built_in">cudaMalloc</span>( (<span class="type">void</span>**)&amp;data.dev_bitmap, bitmap.<span class="built_in">image_size</span>() ) );</span><br><span class="line"></span><br><span class="line">    bitmap.<span class="built_in">anim_and_exit</span>( (<span class="built_in">void</span> (*)(<span class="type">void</span>*,<span class="type">int</span>))generate_frame, (<span class="built_in">void</span> (*)(<span class="type">void</span>*))cleanup );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>4.9 共享内存： <code>CUDA</code>可以在声明时通过<code>__shared__</code>关键字,使变量驻留在共享内存中。共享内存中的变量可以被同一线程块中的线程所共享，所以可以通过共享内存来实现同一线程块中的线程之间进行通信，且共享内存位于物理GPU上，其访问延迟要远远低于普通缓冲区。使用方法即是将<code>__shared__</code>添加到变量声明中。  </p>
<p>4.10 <code>CUDA</code>可以使用线程同步机制<code>__syncthreads();</code>对线程块中的线程进行同步。该函数可以确保同一线程块中的所有线程在执行完该语句之前的所有语句之后才会执行其下一条语句。使用<code>__syncthreads();</code>时一定要时刻记住避免由于线程发散所引起的线程永久等待问题。线程发散是指由于某种判断导致某些线程需要执行一些指令，而其他线程不需要执行这条指令的情况。例如：<code>if (threadIdx.x % 2) myvar = threadIdx.x;</code>这将导致奇数线程需要执行，而偶数线程不需要执行。但在这个时候如果将<code>__syncthreads();</code>函数放在<code>if</code>语句中，就必然会导致有些线程需要执行到<code>__syncthreads();</code>的情况，此时当奇数线程执行到这里时它需要等待其他线程也执行到该语句，但由于<code>if</code>语句的判断，会导致它永远等不到偶数线程来执行<code>__syncthreads();</code>函数，这样就会引起处理器挂起的情况。</p>
<p>4.11 时刻记得<code>CUDA</code>是使用GPU进行并行计算，所有线程格所组织的线程块中的所有线程都在同时执行同一个核函数。在对共享内存写入时要记得确保所有线程都已经执行完成，避免发生竞态条件。竞态条件是指对于共享内存中的数据，有可能线程A和线程B会同时对该共享数据进行操作，那么，在这种情况下代码的执行结果将是不确定的。CUDA中避免同一个线程块中线程访问shared memory出现竞态条件的方法是使用<code>__syncthreads()</code>在读取shared memory的值之前进行线程同步。</p>
<p>4.12 关于书上点积运算的例子中在求和归约运算时需要使用<code>__syncthreads();</code>的解释，详细看下图以及4.13中实例分析，注意当前该线程块中的所有线程都在运行这个核函数，且每个线程块都会有其自己的一个共享内存区域，只有同一个线程块中的线程之间才能共享该线程块的共享内存。<br><img data-src="syncthreads.jpg" alt="线程协作"><br>由于所有线程同时并行运行所以并不一定线程0就先计算，但对应关系一定是这样，且通过与<code>i</code>比较来筛选出索引小于<code>i</code>的线程进行计算。每次循环线程数减半，直到最后所有的值都加到cache[0]中</p>
<p>4.13 <code>threadIdx.x</code>是个内置变量，存储了当前线程所在线程块中的索引，也就是说它是核函数中唯一能表征当前时刻该核函数正在被哪个线程所执行，且该变量是个常量。它的值是相对于线程块的，在同一个线程块中其值是唯一的，每个线程块都会存在对应值相等的<code>threadIdx.x</code>。将其与线程块和线程格结合起来便能确定出一个唯一的线程索引。</p>
<p>4.14 点积运算实例的详细说明，其中用到了一些之前没有用过的方法，程序还有很多可以改善的地方：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> min(a,b) (a&lt;b?a:b)  <span class="comment">//用于确定线程格中线程块的数量</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">const</span> <span class="type">int</span> N = <span class="number">33</span> * <span class="number">1024</span>;</span><br><span class="line"><span class="type">const</span> <span class="type">int</span> threadsPerBlock = <span class="number">256</span>;  <span class="comment">/*N应尽量为线程块中线程数的整数倍，以确保刚好每个线程都在参与计算，</span></span><br><span class="line"><span class="comment">又由于后面需要使用归约运算求和，所以其必须为2的指数。*/</span></span><br><span class="line"><span class="type">const</span> <span class="type">int</span> blocksPerGrid = <span class="built_in">min</span>(<span class="number">32</span>, (N+threadsPerBlock<span class="number">-1</span>)/threadsPerBlock);  </span><br><span class="line"><span class="comment">/*为了性能要求确保每个线程格中的线程块数量不超过32。</span></span><br><span class="line"><span class="comment">当线程块过多时会导致产生过多的线程使GPU非常繁忙而CPU却有空闲。其实此处明显其值为32*/</span></span><br><span class="line"></span><br><span class="line"><span class="function">__global__ <span class="type">void</span> <span class="title">dot</span><span class="params">(<span class="type">float</span> *a, <span class="type">float</span> *b, <span class="type">float</span> *c)</span>  <span class="comment">//a,b为输入数据，c为计算结果</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">//在共享内存为每个线程块声明一个cache数组用于存放每个线程计算的结果</span></span><br><span class="line">    __shared__ <span class="type">float</span> cache[threadsPerBlock];</span><br><span class="line"></span><br><span class="line">    <span class="comment">//通过线程块索引和线程索引计算出输入数组中的全局偏移，也就是确定当前该线程该去计算哪个数组的元素了。</span></span><br><span class="line">    <span class="type">int</span> tid = threadIdx.x + blockIdx.x * blockDim.x;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/*cache的大小刚好就是线程块中所包含的线程数量，所以cache中的</span></span><br><span class="line"><span class="comment">    每个元素刚好可以与线程一一对应，threadIdx.x就是当前执行该核函数的线程所在线程块中的索引*/</span></span><br><span class="line">    <span class="type">int</span> cacheIndex = threadIdx.x;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/*由于一个线程有可能执行多次求积的运算，所以可以用它临时存放该线程所计算的积，</span></span><br><span class="line"><span class="comment">    最后再将该线程计算的所有积累加存入共享内存中的数组cache*/</span></span><br><span class="line">    <span class="type">float</span> temp = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span> (tid &lt; N)</span><br><span class="line">    &#123;</span><br><span class="line">        temp += a[tid] * b[tid];</span><br><span class="line">        tid += blockDim.x * gridDim.x;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/*在该线程计算完成之后将其计算过的所有积的累加和存入数组。</span></span><br><span class="line"><span class="comment">    此处应该可以将前面声明的cacheIndex省略，而直接使用threadIdx.x作为数组索引。*/</span></span><br><span class="line">    cache[cacheIndex] = temp;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//对线程块中的线程进行同步，确保所有线程都已经将其计算的值存入了共享内存中</span></span><br><span class="line">    __syncthreads();</span><br><span class="line">    <span class="comment">/*也就是说到此为止所有的积都已经计算完了，下面想办法将它们累加起来就可以。</span></span><br><span class="line"><span class="comment">    当前的情况为一共有32个线程块，而每个线程块中都有一个大小为256的cache数组，</span></span><br><span class="line"><span class="comment">    也就是说有32 x 256个值需要累加。当然可以直接使用一个线程对它们进行一一迭代32 x 256次，</span></span><br><span class="line"><span class="comment">    既然使用了GPU必然有更好的方法，那就是归约，归约的目的是对一个输入数组执行某种计算，</span></span><br><span class="line"><span class="comment">    然后产生一个更小的结果数组，类似于算法中的归并策略。此处使用并行的方法来执行归约计算，</span></span><br><span class="line"><span class="comment">    即每个线程块中前1/2的线程将cache[]中的对应于其索引的元素的值与cache[]中后面1/2的值进行累加，</span></span><br><span class="line"><span class="comment">    然后依次循环为前1/2的1/2线程执行同样的操作，所以前面要求threadsPerBlock必须为2的指数，具体参见3.11图。*/</span></span><br><span class="line"></span><br><span class="line">    <span class="type">int</span> i = blockDim.x / <span class="number">2</span>;</span><br><span class="line">    <span class="keyword">while</span> (i != <span class="number">0</span>)  <span class="comment">//直到所有值都加到了cache[0]中</span></span><br><span class="line">    &#123;</span><br><span class="line">	<span class="comment">//防止索引越界,由于无法确定哪个线程先计算，所以也同时相当于挑选那些索引在i之前的线程进行计算。</span></span><br><span class="line">	<span class="keyword">if</span> (cacheIndex &lt; i)</span><br><span class="line">	&#123;</span><br><span class="line">            cache[cacheIndex] += cache[cacheIndex + i];</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//确保所有对共享内存的写操作都完成了，注意不能将它放入if中，以免发生处理器挂起的情况</span></span><br><span class="line">        __syncthreads();</span><br><span class="line"></span><br><span class="line">        i /= <span class="number">2</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//至此每一个线程块中线程的计算结果都放入了其对应共享内存的cache[0]中</span></span><br><span class="line">    <span class="comment">/*使用线程索引为0的线程将计算结果存入结果数组c中，当然可以使用任意一个线程完成这个工作，</span></span><br><span class="line"><span class="comment">    也可以不加个条件判断而让所有线程同时执行这个操作，但这将增加很多额外的通信量。*/</span></span><br><span class="line">    <span class="keyword">if</span> (cacheIndex == <span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">	c[blockIdx.x] = cache[<span class="number">0</span>];  <span class="comment">//每个线程块都有一个cache[]数组</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/*至此乘积的计算结果被分成了32份放入了数组c中，然后使用CPU进行累加就可以了。</span></span><br><span class="line"><span class="comment">    不使用GPU的多线程是因为计算量太小，如果使用GPU的话会导致很多线程处于空闲状态，浪费资源。*/</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">(<span class="type">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">float</span> *a, *b, *partial_c;  </span><br><span class="line">    <span class="comment">/*注意此处并没有直接声明为数组，而是声明的指针。因为malloc分配的空间是在堆上，</span></span><br><span class="line"><span class="comment">    直接声明为数组时分配的内存却是在栈上。虽然对于栈的操作效率更高，但堆上可以分配的空间更大，</span></span><br><span class="line"><span class="comment">    堆上分配的内存记得要手动释放*/</span></span><br><span class="line">    pass;  <span class="comment">//省略</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>更多关于共享内存的内容参见官方DOC: <a target="_blank" rel="noopener" href="http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#shared-memory">http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#shared-memory</a></p>
<h2 id="常量内存-事件"><a href="#常量内存-事件" class="headerlink" title="常量内存|事件"></a>常量内存|事件</h2><p>5.1 <code>CUDA</code>使用关键字<code>__constant__</code>声明常量内存中的变量，常量内存只读，但效率高且可以节约内存带宽,所以常量内存适合存放需要大量只读调用的常量数据。声明常量内存时必须指定数组大小，eg: <code>__constant__ type arr[15];</code>。<code>cudaMalloc()</code>分配的为全局内存，即设备内存。</p>
<p>5.2 将数据从主机内存复制到GPU上的常量内存需要使用<code>cudaMemcpyToSymbol()</code>函数，eg: <code>cudaMemcpyToSymbol(tar, src, size);</code>不需要指定方向。</p>
<p>5.3 <code>CUDA</code>架构中，线程束是指一个包含32个线程的集合(高版本的指令集支持指定线程束数量及重新排列线程束中线程的顺序)，同一个线程束中的线程会以“步调一致(Lockstep)”的形式执行,即在程序中的每一行，线程束中的每个线程都将在不同的数据上执行相同的指令，有点类似SIMD。半线程束即指线程束的一半，也就是16个线程。</p>
<p>5.4 常量内存具有两个特点：</p>
<ul>
<li>对常量内存的单次操作可以广播到其他邻近的15个线程中，也就是每次操作常量内存就相当于半线程束在同时操作常量内存，所以这将节约15次读取操作。</li>
<li>常量内存的数据将被缓存起来，因此对相同地址的连续读操作将不会产生额外的内存消耗。</li>
</ul>
<p>5.5 常量内存是一把双刃剑因为当半线程束需要访问常量内存中的不同数据时，这16次不同的读取操作会被串行化，而如果是从全局内存中读取，则会以并行方式同时进行。</p>
<p>5.6 <code>CUDA</code>使用事件来测量性能，事件本质上是GPU时间戳，由于可能会执行一些异步函数调用，所以在读取时间记录之前必须使用<code>cudaEventSynchronize()</code>函数对事件进行同步。<code>CUDA</code>事件是直接在GPU上实现的，所以它不能用于同时包含设备代码和主机代码的混合代码。eg:  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">cudaEvent_t start, stop;  <span class="comment">//声明两个事件时间变量</span></span><br><span class="line"><span class="built_in">cudaEventCreate</span>(&amp;start);  <span class="comment">//创建起始事件</span></span><br><span class="line"><span class="built_in">cudaEventCreate</span>(&amp;stop);  <span class="comment">//创建结束事件</span></span><br><span class="line"><span class="built_in">cudaEventRecord</span>(start, <span class="number">0</span>); <span class="comment">//记录开始事件时间</span></span><br><span class="line"><span class="comment">//在GPU上执行一些工作</span></span><br><span class="line"><span class="built_in">cudaEventRecord</span>(stop, <span class="number">0</span>); <span class="comment">//记录结束事件时间</span></span><br><span class="line"><span class="built_in">cudaEventSynchronize</span>(stop); <span class="comment">//同步结束事件，确保所有对stop事件的操作已经完成</span></span><br><span class="line"><span class="type">float</span> elapsedTime;  <span class="comment">//用于存放事件所使用的时间</span></span><br><span class="line"><span class="built_in">cudaEventElapsedTime</span>(&amp;elapsedTime, start, stop);  <span class="comment">//计算两个事件之间所经历的时间,单位为毫秒</span></span><br><span class="line">std::cout &lt;&lt; elapsedTime;  <span class="comment">//输出时间</span></span><br><span class="line"><span class="built_in">cudaEventDestroy</span>(start);  <span class="comment">//销毁事件，相当于释放资源</span></span><br><span class="line"><span class="built_in">cudaEventDestroy</span>(stop);  </span><br></pre></td></tr></table></figure>

<h2 id="纹理内存和表面-Texture-and-Surface-Memory"><a href="#纹理内存和表面-Texture-and-Surface-Memory" class="headerlink" title="纹理内存和表面(Texture and Surface Memory)"></a>纹理内存和表面(Texture and Surface Memory)</h2><h3 id="Texture-Memory"><a href="#Texture-Memory" class="headerlink" title="Texture Memory"></a>Texture Memory</h3><p>6.1 纹理内存是CUDA中的另一种只读内存，同样缓存在芯片上，在特定的模式中可以提高性能并减少内存通信量，因为虽然他的分配实际也是在global memory，但它有cache，只有当cache没有命中时才会去访问device memory。它的特点是其专门用于那些在访问模式中存在大量空间局部性的图形应用程序而设计。这里的空间局部性是指某个线程读取的位置可能与邻近线程读取的位置“非常接近”，这些位置不一定要像常量内存那样都是连续的而是指可以前后左右相邻。所以纹理内存非常适合用于图像的处理。纹理内存也可以被layered，称为<code>Layered Textures</code></p>
<p>6.2 CUDA中有2种不同的方式来存取纹理内存和surface内存：</p>
<ul>
<li>纹理引用API（texture reference API），该API支持所有设备，也就是本文原来介绍的方式。该方式的纹理引用创建在编译期，所以需要在创建时指定大小。</li>
<li>纹理对象API（texture object API），该API只支持计算能力3.x以上的设备。纹理对象的创建发生在运行时。</li>
</ul>
<h4 id="Texture-Object-API"><a href="#Texture-Object-API" class="headerlink" title="Texture Object API"></a>Texture Object API</h4><p>该方式使用纹理内存的过程主要分为4步：1）分配device memory，2）通过device memory创建纹理对象，3）访问纹理内存，4）销毁纹理对象并释放device内存。<br>Texture对象使用函数<code>cudaCreateTextureObject()</code>从源描述结构体<code>cudaResourceDesc</code>创建，并通过texture描述结构体<code>cudaTextureDesc</code>指定texture对象的参数。该函数的原型：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">__host__ cudaError_t <span class="title">cudaCreateTextureObject</span> <span class="params">( cudaTextureObject_t* pTexObject, <span class="type">const</span> cudaResourceDesc* pResDesc, <span class="type">const</span> cudaTextureDesc* pTexDesc, <span class="type">const</span> cudaResourceViewDesc* pResViewDesc )</span></span></span><br></pre></td></tr></table></figure>
<p>其中<code>cudaResourceDesc</code>中可以用于指定device memory内存地址，以及相应的内存类型。当用于二维图像时，通常可以将<code>cudaResourceDesc::resType</code>设置为<code>cudaResourceTypePitch2D</code>，然后设置其相应的宽高等，下面是一个实例中对于YUV图像处理时使用纹理内存的<code>cudaResourceDesc</code>的初始化方法：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> hhSrc = nSrcHeight * <span class="number">3</span> / <span class="number">2</span>;  <span class="comment">// nSrcHeight为原图像的高</span></span><br><span class="line"></span><br><span class="line">cudaResourceDesc resDesc = &#123;&#125;;</span><br><span class="line">resDesc.resType = cudaResourceTypePitch2D;</span><br><span class="line">resDesc.res.pitch2D.devPtr = dpSrc;  <span class="comment">// dpSrc为device memory中的设备内存指针</span></span><br><span class="line">resDesc.res.pitch2D.desc = <span class="built_in">cudaCreateChannelDesc</span>&lt;<span class="type">uint8_t</span>&gt;();</span><br><span class="line">resDesc.res.pitch2D.width = nSrcWidth;</span><br><span class="line">resDesc.res.pitch2D.height = hhSrc * nBatchSize;</span><br><span class="line">resDesc.res.pitch2D.pitchInBytes = nSrcPitch;</span><br></pre></td></tr></table></figure>
<p>关于该函数的详细描述可以看这里：<a target="_blank" rel="noopener" href="http://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__TEXTURE__OBJECT.html">http://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__TEXTURE__OBJECT.html</a><br>NV官方一个示例的完整代码及注释如下：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Simple transformation kernel</span></span><br><span class="line"><span class="function">__global__ <span class="type">void</span> <span class="title">transformKernel</span><span class="params">(<span class="type">float</span>* output,</span></span></span><br><span class="line"><span class="params"><span class="function">                                cudaTextureObject_t texObj,</span></span></span><br><span class="line"><span class="params"><span class="function">                                <span class="type">int</span> width, <span class="type">int</span> height,</span></span></span><br><span class="line"><span class="params"><span class="function">                                <span class="type">float</span> theta)</span> </span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// Calculate normalized texture coordinates</span></span><br><span class="line">    <span class="type">unsigned</span> <span class="type">int</span> x = blockIdx.x * blockDim.x + threadIdx.x;</span><br><span class="line">    <span class="type">unsigned</span> <span class="type">int</span> y = blockIdx.y * blockDim.y + threadIdx.y;</span><br><span class="line"></span><br><span class="line">    <span class="type">float</span> u = x / (<span class="type">float</span>)width;</span><br><span class="line">    <span class="type">float</span> v = y / (<span class="type">float</span>)height;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Transform coordinates</span></span><br><span class="line">    u -= <span class="number">0.5f</span>;</span><br><span class="line">    v -= <span class="number">0.5f</span>;</span><br><span class="line">    <span class="type">float</span> tu = u * <span class="built_in">cosf</span>(theta) - v * <span class="built_in">sinf</span>(theta) + <span class="number">0.5f</span>;</span><br><span class="line">    <span class="type">float</span> tv = v * <span class="built_in">cosf</span>(theta) + u * <span class="built_in">sinf</span>(theta) + <span class="number">0.5f</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 读取纹理内存到global memory</span></span><br><span class="line">    output[y * width + x] = <span class="built_in">tex2D</span>&lt;<span class="type">float</span>&gt;(texObj, tu, tv);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// Host code</span></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// 在device memory中分配CUDA array</span></span><br><span class="line">    cudaChannelFormatDesc channelDesc =</span><br><span class="line">               <span class="built_in">cudaCreateChannelDesc</span>(<span class="number">32</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>,</span><br><span class="line">                                     cudaChannelFormatKindFloat);</span><br><span class="line">    cudaArray* cuArray;</span><br><span class="line">    <span class="built_in">cudaMallocArray</span>(&amp;cuArray, &amp;channelDesc, width, height);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 将主机上位于h_data中的数据拷贝到设备内存上的cuda array中</span></span><br><span class="line">    <span class="built_in">cudaMemcpyToArray</span>(cuArray, <span class="number">0</span>, <span class="number">0</span>, h_data, size,</span><br><span class="line">                      cudaMemcpyHostToDevice);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 初始化texture的device内存源描述信息并指定device memory地址</span></span><br><span class="line">    <span class="comment">// 这里是使用的cuda array</span></span><br><span class="line">    <span class="keyword">struct</span> <span class="title class_">cudaResourceDesc</span> resDesc;</span><br><span class="line">    <span class="built_in">memset</span>(&amp;resDesc, <span class="number">0</span>, <span class="built_in">sizeof</span>(resDesc));</span><br><span class="line">    resDesc.resType = cudaResourceTypeArray;</span><br><span class="line">    resDesc.res.array.array = cuArray;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 指定texture的参数信息</span></span><br><span class="line">    <span class="keyword">struct</span> <span class="title class_">cudaTextureDesc</span> texDesc;</span><br><span class="line">    <span class="built_in">memset</span>(&amp;texDesc, <span class="number">0</span>, <span class="built_in">sizeof</span>(texDesc));</span><br><span class="line">    texDesc.addressMode[<span class="number">0</span>]   = cudaAddressModeWrap;</span><br><span class="line">    texDesc.addressMode[<span class="number">1</span>]   = cudaAddressModeWrap;</span><br><span class="line">    texDesc.filterMode       = cudaFilterModeLinear;</span><br><span class="line">    texDesc.readMode         = cudaReadModeElementType;</span><br><span class="line">    texDesc.normalizedCoords = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建texture对象</span></span><br><span class="line">    cudaTextureObject_t texObj = <span class="number">0</span>;</span><br><span class="line">    <span class="built_in">cudaCreateTextureObject</span>(&amp;texObj, &amp;resDesc, &amp;texDesc, <span class="literal">NULL</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 分配变换结果所需要的device memory</span></span><br><span class="line">    <span class="type">float</span>* output;</span><br><span class="line">    <span class="built_in">cudaMalloc</span>(&amp;output, width * height * <span class="built_in">sizeof</span>(<span class="type">float</span>));</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Invoke kernel</span></span><br><span class="line">    <span class="function">dim3 <span class="title">dimBlock</span><span class="params">(<span class="number">16</span>, <span class="number">16</span>)</span></span>;</span><br><span class="line">    <span class="function">dim3 <span class="title">dimGrid</span><span class="params">((width  + dimBlock.x - <span class="number">1</span>) / dimBlock.x,</span></span></span><br><span class="line"><span class="params"><span class="function">                 (height + dimBlock.y - <span class="number">1</span>) / dimBlock.y)</span></span>;</span><br><span class="line">    transformKernel&lt;&lt;&lt;dimGrid, dimBlock&gt;&gt;&gt;(output,</span><br><span class="line">                                           texObj, width, height,</span><br><span class="line">                                           angle);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 销毁纹理对象</span></span><br><span class="line">    <span class="built_in">cudaDestroyTextureObject</span>(texObj);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 释放显存</span></span><br><span class="line">    <span class="built_in">cudaFreeArray</span>(cuArray);</span><br><span class="line">    <span class="built_in">cudaFree</span>(output);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="Texture-Reference-API"><a href="#Texture-Reference-API" class="headerlink" title="Texture Reference API"></a>Texture Reference API</h4><p>注意该模式下的texture引用变量只能为全局变量，不支持通过参数的形式传递为局部变量。<br>该方式下的纹理内存使用主要分为4个步骤：1）device memory分配，2）创建texture，并与分配的显存绑定，3）读取纹理内存，4）解绑并释放分配的显存。<br>创建texture的模板原型如下，其中<code>Type</code>和<code>ReadMode</code>两个为可选参数，具体作用参考官方文档。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">texture&lt;DataType, Type, ReadMode&gt; texRef;</span><br></pre></td></tr></table></figure>
<p>此处为一维纹理内存使用过程举例：<br>显存绑定：首先需要将输入的数据声明为<code>texture</code>类型的引用,eg: <code>texture&lt;float&gt; texIn;</code>表示声明一个<code>float</code>类型的纹理引用，引用名为<code>texIn</code>，纹理引用必须声明为文件作用域内的全局变量。注意这里仅仅是声明了一个引用，并没有分配内存空间。然后就需要使用<code>cudaBindTexture()</code>函数将引用变量绑定到内存缓冲区，此处的内存缓冲区依然需要使用<code>cudaMalloc()</code>来分配，<code>cudaBindTexture()</code>做的工作有将指定的缓冲区作为纹理内存来使用以及将纹理引用作为纹理的“名字”。<br>读取：纹理内存分配完成之后就可以使用了，纹理内存的读取不能像数组那样直接使用下标引用,而是使用内置函数<code>text1Dfetch(cudaTextureObject_t texObj, int x)</code>进行读取，<code>texObj</code>表示纹理对象，<code>x</code>表示整型纹理坐标，其实就是用全局偏移<code>offset</code>来指定的方向。<br>释放：使用内置函数<code>cudaUnbindTexture()</code>解除与纹理的绑定然后再释放内存即可。<br>eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">texture&lt;<span class="type">float</span>&gt; texIn;  <span class="comment">//声明一个float类型的纹理引用</span></span><br><span class="line"><span class="built_in">cudaMalloc</span>((<span class="type">void</span>**)&amp;date.dev_inSrc, imageSize);  <span class="comment">//分配一块打算作为纹理内存的空间</span></span><br><span class="line"><span class="built_in">cudaBindTexture</span>(<span class="literal">NULL</span>, texIn, date.dev_inSrc, imageSize);  <span class="comment">//将纹理引用与内存空间绑定并希望将指定的空间作为纹理内存使用</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> x = threadIdx.x + blockIdx.x * blockDim.x;</span><br><span class="line"><span class="type">int</span> y = threadIdx.y + blockIdx.y * blockDim.y;</span><br><span class="line"><span class="type">int</span> offset = x + y * blockDim.x * gridDim.x;</span><br><span class="line"><span class="type">int</span> top = offset - DIM;  <span class="comment">//定义需要处理的当前像素位置的上方的元素位置(DIM X DIM大小的画布),默认坐标(x, y)为中心数据</span></span><br><span class="line"><span class="type">float</span> t;  <span class="comment">//用于存放从纹理内存中读取的值</span></span><br><span class="line">t = <span class="built_in">text1Dfetch</span>(texIn, top);  <span class="comment">//读取纹理内存中的数据到t中</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">cudaUnbindTexture</span>(texIn);  <span class="comment">//解除绑定</span></span><br><span class="line"><span class="built_in">cudaFree</span>(d-&gt;dev_inSrc);  </span><br></pre></td></tr></table></figure>

<p>声明的纹理引用可以在使用完之后解绑定，然后再将其与其他内存空间进行绑定，<code>cudaBindTexture()</code>的函数原型为</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">cudaBindTexture</span> ( <span class="type">size_t</span>* offset, <span class="type">const</span> textureReference* texref, <span class="type">const</span> <span class="type">void</span>* devPtr, <span class="type">const</span> cudaChannelFormatDesc* desc, <span class="type">size_t</span> size = UINT_MAX )</span><br></pre></td></tr></table></figure>

<p>官方文档建议使用二维的纹理内存。Read more at: <a target="_blank" rel="noopener" href="http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#texture-memory">http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#texture-memory</a><br>NV官方与上面texture对象的方式使用纹理内存一样功能的一个示例：  </p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建全局的texture引用</span></span><br><span class="line">texture&lt;<span class="type">float</span>, cudaTextureType2D, cudaReadModeElementType&gt; texRef;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Simple transformation kernel</span></span><br><span class="line"><span class="function">__global__ <span class="type">void</span> <span class="title">transformKernel</span><span class="params">(<span class="type">float</span>* output,</span></span></span><br><span class="line"><span class="params"><span class="function">                                <span class="type">int</span> width, <span class="type">int</span> height,</span></span></span><br><span class="line"><span class="params"><span class="function">                                <span class="type">float</span> theta)</span> </span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// Calculate normalized texture coordinates</span></span><br><span class="line">    <span class="type">unsigned</span> <span class="type">int</span> x = blockIdx.x * blockDim.x + threadIdx.x;</span><br><span class="line">    <span class="type">unsigned</span> <span class="type">int</span> y = blockIdx.y * blockDim.y + threadIdx.y;</span><br><span class="line"></span><br><span class="line">    <span class="type">float</span> u = x / (<span class="type">float</span>)width;</span><br><span class="line">    <span class="type">float</span> v = y / (<span class="type">float</span>)height;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Transform coordinates</span></span><br><span class="line">    u -= <span class="number">0.5f</span>;</span><br><span class="line">    v -= <span class="number">0.5f</span>;</span><br><span class="line">    <span class="type">float</span> tu = u * <span class="built_in">cosf</span>(theta) - v * <span class="built_in">sinf</span>(theta) + <span class="number">0.5f</span>;</span><br><span class="line">    <span class="type">float</span> tv = v * <span class="built_in">cosf</span>(theta) + u * <span class="built_in">sinf</span>(theta) + <span class="number">0.5f</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">// Read from texture and write to global memory</span></span><br><span class="line">    output[y * width + x] = <span class="built_in">tex2D</span>(texRef, tu, tv);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Host code</span></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// 在device memory中分配CUDA array</span></span><br><span class="line">    cudaChannelFormatDesc channelDesc =</span><br><span class="line">               <span class="built_in">cudaCreateChannelDesc</span>(<span class="number">32</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>,</span><br><span class="line">                                     cudaChannelFormatKindFloat);</span><br><span class="line">    cudaArray* cuArray;</span><br><span class="line">    <span class="built_in">cudaMallocArray</span>(&amp;cuArray, &amp;channelDesc, width, height);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 将主机上位于h_data中的数据拷贝到设备内存上的cuda array中</span></span><br><span class="line">    <span class="built_in">cudaMemcpyToArray</span>(cuArray, <span class="number">0</span>, <span class="number">0</span>, h_data, size,</span><br><span class="line">                      cudaMemcpyHostToDevice);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 设置texture引用的参数</span></span><br><span class="line">    texRef.addressMode[<span class="number">0</span>] = cudaAddressModeWrap;</span><br><span class="line">    texRef.addressMode[<span class="number">1</span>] = cudaAddressModeWrap;</span><br><span class="line">    texRef.filterMode     = cudaFilterModeLinear;</span><br><span class="line">    texRef.normalized     = <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 绑定刚才创建cuArray到纹理引用</span></span><br><span class="line">    <span class="built_in">cudaBindTextureToArray</span>(texRef, cuArray, channelDesc);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 分配变换结果所需要的device memory</span></span><br><span class="line">    <span class="type">float</span>* output;</span><br><span class="line">    <span class="built_in">cudaMalloc</span>(&amp;output, width * height * <span class="built_in">sizeof</span>(<span class="type">float</span>));</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Invoke kernel</span></span><br><span class="line">    <span class="function">dim3 <span class="title">dimBlock</span><span class="params">(<span class="number">16</span>, <span class="number">16</span>)</span></span>;</span><br><span class="line">    <span class="function">dim3 <span class="title">dimGrid</span><span class="params">((width  + dimBlock.x - <span class="number">1</span>) / dimBlock.x,</span></span></span><br><span class="line"><span class="params"><span class="function">                 (height + dimBlock.y - <span class="number">1</span>) / dimBlock.y)</span></span>;</span><br><span class="line">    transformKernel&lt;&lt;&lt;dimGrid, dimBlock&gt;&gt;&gt;(output, width, height,</span><br><span class="line">                                           angle);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 释放device memory</span></span><br><span class="line">    <span class="built_in">cudaFreeArray</span>(cuArray);</span><br><span class="line">    <span class="built_in">cudaFree</span>(output);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>6.3 二维纹理内存，由于此处是在处理<code>DIM x DIM</code>大小的图像问题，所以这里使用二维纹理内存更加合适，官方也建议尽量使用二维纹理内存。首先要清楚这里处理热传递问题有点类似<code>5-point stencil</code>的问题，即以坐标(x, y)为中心，然后对其上下左右的数据进行调用，刚好也是个二维平面。二维纹理内存的使用同样需要一维中的三大步。只是内置函数变化一下，而且不需要再使用全局偏移来定义位置，因为内存刚好也是二维的。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">texture&lt;<span class="type">float</span>, <span class="number">2</span>&gt; texIn;  <span class="comment">//声明一个float类型的二维纹理内存引用</span></span><br><span class="line"><span class="built_in">cudaMalloc</span>((<span class="type">void</span>**)&amp;date.dev_inSrc, imageSize);  <span class="comment">//分配一块打算作为纹理内存的空间</span></span><br><span class="line"><span class="comment">//将二维纹理引用与内存空间绑定并希望将指定的空间作为纹理内存使用</span></span><br><span class="line"><span class="built_in">cudaBindTexture2D</span>(<span class="literal">NULL</span>, texIn, date.dev_inSrc, desc, DIM, DIM, DIM * <span class="built_in">sizeof</span>(<span class="type">float</span>)); </span><br><span class="line"></span><br><span class="line"><span class="type">int</span> x = threadIdx.x + blockIdx.x * blockDim.x;</span><br><span class="line"><span class="type">int</span> y = threadIdx.y + blockIdx.y * blockDim.y;</span><br><span class="line"><span class="type">int</span> offset = x + y * blockDim.x * gridDim.x;</span><br><span class="line"><span class="type">float</span> t;  <span class="comment">//用于存放从纹理内存中读取的值</span></span><br><span class="line">t = <span class="built_in">text2D</span>(texIn, x, y<span class="number">-1</span>);  <span class="comment">//读取二维纹理内存中的数据到t中，注意(x, y)为中心，它上面的元素自然就是(x, y-1)</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">cudaUnbindTexture</span>(texIn);  <span class="comment">//解除绑定</span></span><br><span class="line"><span class="built_in">cudaFree</span>(d-&gt;dev_inSrc);  </span><br></pre></td></tr></table></figure>
<p>关于纹理内存使用的官方DOC：<a target="_blank" rel="noopener" href="http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__TEXREF.html#axzz3ggCvFftU">http://docs.nvidia.com/cuda/cuda-driver-api/group__CUDA__TEXREF.html#axzz3ggCvFftU</a></p>
<p>6.4 纹理内存选择一维还是二维应根据具体情况而定，哪个<code>coding</code>起来更方便就选择哪个，其对基本没有区别。</p>
<h3 id="Surface-Memory"><a href="#Surface-Memory" class="headerlink" title="Surface Memory"></a>Surface Memory</h3><p>Surface Memory的使用与纹理非常像，以后用到了再了解吧，官方使用文档在此<a target="_blank" rel="noopener" href="http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#surface-memory">http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#surface-memory</a></p>
<h2 id="图形互操作性"><a href="#图形互操作性" class="headerlink" title="图形互操作性"></a>图形互操作性</h2><p>7.1 主要介绍<code>CUDA</code>可以执行通用计算将以前需要依赖CPU进行的图像渲染工作由GPU实现。这样的好处是首先GPU的并行性使得速度通常会更高，另一方面可以使CPU空闲出来做其他工作。这里主要介绍了<code>CUDA</code>与<code>OpenGL</code>的图形互操作，以及<code>CUDA C</code>核函数与<code>OpenGL</code>渲染函数之间共享数据。所以用到了大量<code>OpenGL</code>的知识，而且也主要是为了实现由GPU进行界面渲染，以后有需要再补充。</p>
<h2 id="原子性"><a href="#原子性" class="headerlink" title="原子性"></a>原子性</h2><p>8.1 计算功能集就是<code>Compute Capability</code>表示<code>NVIDIA GPU</code>所能支持的最高指令集版本。可以通过<code>cudaDeviceProp prop</code>结构体的<code>prop.major</code>和<code>prop.minor</code>来查看，我的机器上是<code>5.0</code>，由于计算功能集是向下兼容的，所以高版本支持所有低版本的指令操作。</p>
<p>8.2 可以通过为<code>nvcc</code>指定参数来告诉编译器所需要的最小计算功能集。例如你编写的程序中用到了3.5版本的某个新指令，而该指令在3.5以下版本中没有，那么可以在编译时加上参数<code>-arch=sm_35</code>，这样做的另一个好处是可以让编译器使用高版本的编译优化。eg: <code>nvcc test.cu -o test -arch=sm_11</code></p>
<p>8.3 原子操作是指由于某些操作的执行过程不能分解为更小的部分，而必须连续的不能被其他线程所中断地执行，我们将满足这种条件限制的操作称为原子操作。例如<code>x++;</code>，即是执行三个步骤：读取x-修改x-写入x，这三个过程一旦被打断，有可能最终获取一个不正确的x，所以就必须确保这三个过程是一个整体的操作。由于GPU线程的并行性导致这种情况很容易存在。</p>
<p>8.4 <code>CUDA</code>中可以使用<code>cudaMemset()</code>函数在GPU上为某块内存指定初始值，类似与<code>C/C++</code>中的<code>memset()</code>，但其返回值为错误码。<code>memset()</code>函数原型为说明：<code>void *memset(void *s, char ch, unsigned n);</code> 将s所指向的某一块内存中的每个字节的内容全部设置为ch指定的ASCII值,块的大小由第三个参数指定,这个函数通常为新申请的内存做初始化工作。</p>
<p>8.5 注意书上在验证GPU计算的直方图与CPU计算的直方图是否一样时巧妙地使用了逆序的方式计算。具体方法就是在GPU计算完直方图之后将计算结果复制回主机内存中。由于GPU计算直方图时字节流中一共有256个元素，设定含有256个元素的数组，字节流中的内容作为数组下标，然后对数组元素进行递增，最终遍历完这些字节之后数组中肯定就保存了各个字节的个数。现在反过来遍历所有数组并对数组元素进行递减，数组下标依然为字节流的内容，当所有字节遍历完是数组的所有元素应该为0，否则GPU计算肯定有问题。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="type">int</span> i=<span class="number">0</span>; i&lt;SIZE；i++)</span><br><span class="line">    histo[buffer[i]]--;  <span class="comment">//histo存放直方图数据，buffer为字节流，SIZE为总字节数</span></span><br><span class="line"><span class="comment">//若GPU计算正确，此时histo中的所有元素应该为0</span></span><br></pre></td></tr></table></figure>
<p>8.6 实现原子操作的内置函数是<code>atomicAdd(addr, y)</code>，该函数将生成一个原子操作序列，这个操作序列包括读取地址<code>addr</code>处的值，将<code>y</code>增加到这个值，以及将结果保存回原地址<code>addr</code>。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#defie SIZE (100*1024*1024)</span></span><br><span class="line"><span class="function">__global__ <span class="type">void</span> <span class="title">histo_kernel</span><span class="params">(<span class="type">unsigned</span> <span class="type">char</span> *buffer, <span class="type">long</span> size, <span class="type">unsigned</span> <span class="type">int</span> *histo)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="type">int</span> i = threadIdx.x + blockIdx.x * blockDim.x;</span><br><span class="line">    <span class="type">int</span> stride = blockDim.x * gridDim.x;</span><br><span class="line">    <span class="keyword">while</span> (i &lt; size)</span><br><span class="line">    &#123;</span><br><span class="line">	<span class="built_in">atomicAdd</span>(&amp;(histo[buffer[i]]), <span class="number">1</span>);  </span><br><span class="line">	<span class="comment">/*核函数调用将启动256个线程，每个线程的初始值都是0到线程数量减1之间，然后对其进行偏移，偏移</span></span><br><span class="line"><span class="comment">	量为已启动线程的总数，直到遍历完所有字节流。所以buffer[i]一定可以遍历完所以字节流，且其值为0到255之间，</span></span><br><span class="line"><span class="comment">	因为一个字节8位*/</span></span><br><span class="line">	i += stride;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个核函数效率非常低，因为这将启动数千个线程同时在全局内存中进行原子操作，而且是操作一个只有256个元素的数组，当数千个个线程尝试访问少量的内存位置时，必将发生大量的线程竞争。为了确保递增操作的原子性，对相同内存位置的操作都将被硬件串行化，极大降低并行带来的性能提升。改进方法就是使用共享内存，因为共享内存中是线程块中的线程之间竞争。</p>
<p>8.7 由于共享内存只能由同一个线程块中的线程之间进行访问，而此例中一个线程块中只有256个线程，而结果数据刚好是256个元素。所以当使用共享内存存储直方图结果时将只有256个线程在256个地址上发生竞争。具体的实现方式是分两个阶段，第一个阶段是每个线程块将计算的它所处理数据的直方图结果保存到一个临时数组，此时线程块之间的操作都是相互独立的，因为它们只能操作自己的那块共享内存。第二个阶段是使用原子操作将每个线程块中的结果保存到全局内存中，因为每个线程都可以访问全局内存。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#defie SIZE (100*1024*1024)</span></span><br><span class="line"><span class="function">__global__ <span class="type">void</span> <span class="title">histo_kernel</span><span class="params">(<span class="type">unsigned</span> <span class="type">char</span> *buffer, <span class="type">long</span> size, <span class="type">unsigned</span> <span class="type">int</span> *histo)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    __shared__ <span class="type">unsigned</span> <span class="type">int</span> temp[<span class="number">256</span>];</span><br><span class="line">    temp[threadIdx.x] = <span class="number">0</span>;  <span class="comment">//利用每个线程将temp初值设置为0</span></span><br><span class="line">    __syncthreads();  <span class="comment">//由于操作共享内存，所以同步线程以确保所以写入操作完成</span></span><br><span class="line"></span><br><span class="line">    <span class="type">int</span> i = threadIdx.x + blockIdx.x * blockDim.x;</span><br><span class="line">    <span class="type">int</span> stride = blockDim.x * gridDim.x;</span><br><span class="line">    <span class="keyword">while</span> (i &lt; size)</span><br><span class="line">    &#123;</span><br><span class="line">	<span class="built_in">atomicAdd</span>(&amp;(temp[buffer[i]]), <span class="number">1</span>);  </span><br><span class="line">	<span class="comment">/*核函数调用将启动256个线程，每个线程的初始值都是0到线程数量减1之间，然后对其进行偏移，偏移</span></span><br><span class="line"><span class="comment">	量为已启动线程的总数，直到遍历完所有字节流。所以buffer[i]一定可以遍历完所以字节流，且其值为0到255之间，</span></span><br><span class="line"><span class="comment">	因为一个字节8位*/</span></span><br><span class="line">	i += stride;</span><br><span class="line">    &#125;</span><br><span class="line">    __syncthreads();  <span class="comment">//每次对共享内存的写入操作之后都要进行线程同步</span></span><br><span class="line">    <span class="built_in">atomicAdd</span>(&amp;(histo[threadIdx.x]), temp[threadIdx.x]);  </span><br><span class="line">    <span class="comment">//利用每个线程将其计算的直方图数据通过全局内存的原子操作增加到最终结果中。</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>8.8 原子操作很简单，只是将需要进行原子操作的运算使用相应的原子操作函数实现即可，但一定要注意由于线程竞争引起的性能降低问题。更多原子操作参见官方DOC: <a target="_blank" rel="noopener" href="http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#axzz3ggCvFftU">http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#axzz3ggCvFftU</a></p>
<h2 id="页锁定主机内存-CUDA流"><a href="#页锁定主机内存-CUDA流" class="headerlink" title="页锁定主机内存|CUDA流"></a>页锁定主机内存|CUDA流</h2><p>9.1 以上所有讨论的GPU并行计算都是在进行数据并行性计算，即使用多个线程在大量的数据上执行同一个任务。另一种并行性即CPU中多线程应用程序的任务并行性，即并行地执行两个或多个不同的任务，如同一个程序下载的同时播放音乐。</p>
<p>9.2 页锁定主机内存是指通过<code>CUDA</code>的<code>cudaHostAlloc()</code>函数来在主机上分配一块页锁定的主机内存，也就是固定在物理内存上的主机内存。通过<code>malloc()</code>函数分配的内存为标准的可分页的(Pagable)主机内存，也就是说这段内存有可能被操作系统通过内存分配技术交换到磁盘上，例如<code>windows</code>上的虚拟内存文件<code>pagefile.sys</code>，<code>windows8</code>上的<code>swapfile.sys</code>以及<code>linux</code>系统中的<code>swap</code>分区。所以被转移到分页文件上的内存在一定程度上会降低程序性能。如果使用页锁定主机内存则可以避免这个问题，从而获得2倍以上的性能提升。但过多的使用页锁定主机内存会影响操作系统性能，导致系统更快地耗尽内存。</p>
<p>9.3 页锁定内存的使用与普通内存使用一样，需要先使用<code>cudaHostAlloc()</code>分配页锁定内存，然后使用<code>cudaFreeHost()</code>释放使用过的页锁定内存。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> *a;</span><br><span class="line"><span class="built_in">cudaHostAlloc</span>((<span class="type">void</span>**)&amp;a, size * <span class="built_in">sizeof</span>(*a), cudaHostAllocDefault);  </span><br><span class="line"><span class="comment">//some operation</span></span><br><span class="line"><span class="built_in">cudaFreeHost</span>(a);</span><br></pre></td></tr></table></figure>
<p>更多关于页锁定内存的内容参见官方DOC: <a target="_blank" rel="noopener" href="http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#page-locked-host-memory">http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#page-locked-host-memory</a></p>
<p>9.4 <code>CUDA</code>流表示一个GPU操作队列，并且该队列中的操作将以指定的顺序指行。可以在流中添加一些操作，例如核函数启动，内存复制，以及事件的启动和结束等，将这些操作添加的流的顺序就是它们的执行顺序。</p>
<p>9.5 <code>CUDA</code>单个流的使用：首先可以通过设备属性中的<code>deviceOverlap</code>字段确定设备是否支持重叠(Device Overlap)功能,支持重叠功能的设备能够在执行核函数的同时在设备与主机之间执行复制操作。使用流之前需要使用<code>cudaStream_t</code>定义流，使用<code>cudaStreamCreate()</code>函数创建流，在异步内存复制以及核函数调用中使用流，然后需要使用<code>cudaStreamSynchronize()</code>函数对指定的流在GPU与主机之间进行同步，以告诉主机在继续执行之前要首先等待GPU执行完成。最后需要在退出程序之前使用<code>cudaStreamDestory()</code>函数销毁对GPU操作进行排队的流。eg:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> N (1024*1024)	<span class="comment">//将需要处理的总数据分成20份，每份大小为N</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> FULL_DATA_SIZE (N*20)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//初始化流</span></span><br><span class="line">cudaStream_t stream;</span><br><span class="line"><span class="built_in">cudaStreamCreate</span>(&amp;stream);</span><br><span class="line"></span><br><span class="line"><span class="comment">//为了简化代码只声明输入数据a，输出数据对应为c</span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> *host_a, *dev_a;</span><br><span class="line"><span class="built_in">cudaMalloc</span>((<span class="type">void</span>**)&amp;dev_a, N * <span class="built_in">sizeof</span>(<span class="type">int</span>));  <span class="comment">//在GPU上分配占需要处理的总数据量1/20的空间</span></span><br><span class="line"><span class="built_in">cudaHostAlloc</span>((<span class="type">void</span>**)&amp;host_a, FULL_DATA_SIZE * <span class="built_in">sizeof</span>(<span class="type">int</span>), cudaHostAllocDefault);  <span class="comment">//在主机页锁内存上分配总数据量的空间</span></span><br><span class="line"><span class="comment">//此处对数组填充</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//通过循环20次将总的数据分成20个小数据块以异步方式复制到GPU进行处理</span></span><br><span class="line"><span class="keyword">for</span> (<span class="type">int</span> i=<span class="number">0</span>; i&lt;FULL_DATA_SIZE; i+=N)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="built_in">cudaMemcpyAsync</span>(dev_a, host_a+i, N * <span class="built_in">sizeof</span>(<span class="type">int</span>), cudaMemcpyHostToDevice, stream); <span class="comment">//将数据从主机页锁内存复制到设备内存</span></span><br><span class="line">   kernel&lt;&lt;&lt;N/<span class="number">256</span>, <span class="number">256</span>, <span class="number">0</span>, stream&gt;&gt;&gt;(dev_a, dev_c);  <span class="comment">//指定流的函数调用</span></span><br><span class="line"></span><br><span class="line">    <span class="built_in">cudaMemcpyAsync</span>(host_c+i, dev_c, N * <span class="built_in">sizeof</span>(<span class="type">int</span>), cudaMemcpyDeviceToHost, stream); <span class="comment">//将处理完的数据复制回页锁内存</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>9.6 <code>cudaMemcpy()</code>是以同步方式执行，即当函数返回时复制操作已经完成，并且输出缓冲区中已经包含了复制进去的数据。而<code>cudaMemcpyAsync()</code>是以异步方式执行，即调用函数时只是放置一个请求，表示在这个流队列中执行一次内存复制操作，告诉GPU在它执行完前面的工作之后开始执行这个工作，所以无法保证当函数返回时复制操作是否已经启动。但可以确定复制操作肯定会在下一个被放入流的操作执行之前执行，例如上例中的核函数调用也在这个流中，那么核函数调用之前肯定会先执行完复制操作。任何被传递给<code>cudaMemcpyAsync()</code>的主机内存指针都必须已经通过<code>cudaHostAlloc()</code>分配好内存。</p>
<p>9.7 为了确保GPU流队列中的操作都已经在主机继续执行之前执行完成，必须使用<code>cudaStreamSynchronize(&amp;stream)</code>来同步指定的流。此处的同步是批让GPU与主机同步，以免CPU开始执行下一条需要用到GPU正在处理的数据指令时GPU却还没有执行完。</p>
<p>9.8 使用多个<code>CUDA</code>流：首先确保GPU支持重叠功能，然后开始调度流即可。需要注意的是使用两个流处理的数据量将是使用单个流的两倍，而且由于硬件中并没有流，而是包含一个或者多个引擎来执行内存复制操作，以及一个引擎来执行核函数，这些引擎也会以队列的形式执行，它们在安排队列执行时有可能出现阻塞的情况，从而导致多个流并不一定会加速程序执行。</p>
<p>9.9 将操作放入流队列的顺序将影响程序性能，应该采用宽度优化方式或者轮流加入流而非深度优先方式将操作放入队列，也就是说应该将两个流中的复制以及核函数调用的操作交替的放入流中以避免由于第0个流复制其结果数据之前必须执行核函数而导致此时内存复制引擎阻塞的情况。根据官方说明将流应用好了可以使程序性能获得近2倍的提升。</p>
<p>更多关于流的内存参见官方DOC: <a target="_blank" rel="noopener" href="http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#streams">http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#streams</a>  </p>
<h2 id="零拷贝内存-可移动的固定内存"><a href="#零拷贝内存-可移动的固定内存" class="headerlink" title="零拷贝内存|可移动的固定内存"></a>零拷贝内存|可移动的固定内存</h2><p>10.1 零拷贝内存是指通过给<code>cudaHostAlloc()</code>函数传递<code>cudaHostAllocMapped</code>参数来在主机内存上分配一块GPU可以直接访问的页锁定内存(或称固定内存)，由于其不需要由主机复制到GPU所以称为零拷贝内存。</p>
<p>10.2 零拷贝内存在使用前应该通过设备属性中的字段<code>canMapHostMemory</code>来判断设备是否支持映射主机内存。如果支持那么还需要通过函数<code>cudaSetDeviceFlags()</code>将<code>CUDA</code>运行时设定为能分配零拷贝内存的状态。eg: <code>cudaSetDeviceFlags(cudaDeviceMapHost);</code></p>
<p>10.3 零拷贝内存的分配与页锁定内存类似，只是在分配时可以通过指定额外的标志<code>cudaHostAllocWriteCombined</code>参数将内存分配为“合并式写入”来提高GPU读取内存时的性能，但是当CPU也需要读取这块内存时，效率会低很多，所以要提前考虑应用程序可能的访问模式来决定是否使用这个参数。eg: <code>cudaHostAlloc((void**)&amp;a, size*sizeof(float), cudaHostAllocWriteCombined | cudaHostAllocMapped);</code></p>
<p>10.4 由于GPU的虚拟内存空间地址映射与CPU不同，而<code>cudaHostAlloc()</code>返回的是CPU上的指针，所以需要调用<code>cudaHostGetDevicePointer()</code>函数来获得这块内存在GPU上的指针。然后就可以将这个指针直接传递给核函数了。eg: <code>cudaHostGetDevicePointer(&amp;dev_a, a, 0);</code></p>
<p>10.5 由于核函数在执行期间，零拷贝内存中的内容是未定义的，CPU无法确定GPU在其上的执行是否完成，所以还需要在核函数调用完成之后调用<code>cudaThreadSynchronize()</code>函数来将CPU与GPU进行同步。该函数的调用不需要指定参数。</p>
<p>10.6 最后就是释放分配的内存，零拷贝内存是通过<code>cudaHostAlloc()</code>分配，所以释放与页锁定内存一样使用<code>cudaFreeHost()</code>即可。</p>
<p>10.7 零拷贝内存的性能提升: 对于独立GPU通常可能无效，对于集成GPU由于GPU与CPU共享系统内存，所以通常可以获得性能提升。但即使是集成GPU零拷贝内存也只有当输入内存和输出内存都只被使用一次时零拷贝内存才能带来性能提升。由于GPU不会缓存零拷贝内存中的内容，所以当需要多次读取内存时，使用零拷贝内存将得不偿失，远不如一开始就直接将数据复制到GPU。而且使用零拷贝内存也同样会固定地占用系统物理内存，最终导致系统性能降低。</p>
<p>10.8 可以通过<code>integrated</code>字段来判断GPU是集成的还是独立的。</p>
<p>10.9 页锁定内存(固定内存)只是对划分他的线程来说这些内存是页锁定的，如果要在线程之间共享指向这块内存的指针，那么其他的线程将把这块内存视为标准的、可分页的内存。这种情况将导致以下两种副作用：1).其他线程在这块内存上执行<code>cudaMemcpy()</code>操作时将按照标准的可分页的内存速率事执行复制操作，这种速率仅为最高传输速率的50%左右。2).当线程试图将<code>cudaMemcpyAsync()</code>调用放入CUDA流队列时将失败，因为该函数需要使用固定内存。</p>
<p>10.10 可以在分配内存时指定标志位<code>cudaHostAllocPortable</code>来将内存指定为可移动的，也就是说在其他线程来看，这块内存都是固定内存。该标志还可以与<code>cudaHostAllocWriteCombined</code>和<code>cudaHostAllocMapped</code>一起使用来将内存分配为可移动的、零拷贝的以及合并式写入等的任意组合。eg: <code>cudaHostAlloc((void**)&amp;a, N*sizeof(float), cudaHostAllocWriteCombined | cudaHostAllocMapped | cudaHostAllocPortable);</code>，记得在分配页锁定内存之前首先要调用<code>cudaSetDevice(device_id);</code>和<code>cudaSetDeviceFlags(cudaDeviceMapHost);</code>来将<code>CUDA</code>运行时设定为可以映射的。同样使用零拷贝内存时需要使用<code>cudaHostGetDevicePointer(&amp;dev_a, a, 0);</code>来获得主机内存的有效设备指针。</p>
<h2 id="多GPU系统上的CUDA-C"><a href="#多GPU系统上的CUDA-C" class="headerlink" title="多GPU系统上的CUDA C"></a>多GPU系统上的CUDA C</h2><p>使用多个GPU只需要使用多个CPU线程即可，即在CPU线程中指定GPU设备ID，让每个CPU线程管理一个GPU设备，然后对计算数据进行根据GPU性能进行划分。</p>
<h2 id="总结与补充"><a href="#总结与补充" class="headerlink" title="总结与补充"></a>总结与补充</h2><h3 id="CUDA的所有内存总结"><a href="#CUDA的所有内存总结" class="headerlink" title="CUDA的所有内存总结"></a><code>CUDA</code>的所有内存总结</h3><p><img data-src="cuda_memories.jpg" alt="CUDA硬件内存访问权限及特性"></p>
<p>图中没有涉及页锁定主机内存(<code>Page-Locked Host Memory</code>)或者固定内存(<code>Pinned Memory</code>)、可移动的固定内存(<code>Portable Pinned Memory</code>)以及零拷贝内存(<code>Zero-Copy Memory</code>)，因为这些内存都是通过映射主机内存而实现的，它们不在<code>CUDA</code>硬件中。</p>
<ul>
<li>全局内存(global memory)空间最大也就是<code>DRAM</code>，主要用于设备与主机之间进行数据通信，其存取延迟较高，所以不适合频繁读写。使用<code>cudaMalloc()</code>分配的就是全局内存。解决其高延迟的方法: 将数据分块然后使用<code>shared-memory</code>、当执行当前数据时预取下一个数据到寄存器中等。</li>
</ul>
<p><strong>对于2D/3D内存建议使用<code>cudaMallocPitch()/cudaMalloc3D()</code></strong><br>为了获取到更好的性能，官方建议使用这2个函数用于分配2D和3D的显存，详见：<br><a target="_blank" rel="noopener" href="http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#device-memory">http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#device-memory</a></p>
<h3 id="CUDA中变量声明总结"><a href="#CUDA中变量声明总结" class="headerlink" title="CUDA中变量声明总结"></a><code>CUDA</code>中变量声明总结</h3><p><img data-src="cuda_memories_usage.jpg" alt="CUDA内存定义方式及生命周期和作用域"><br>其中生命周期为<code>kernel</code>的必须在<code>kernel</code>函数中声明且仅仅在这个核函数中是有效的，生命周期为<code>Application</code>的变量必须在任何函数外部声明。注意不属于任何函数，且声明于全局内存和常量内存中的变量可以被主机访问，常量内存在大小被限制为<code>64KB</code>。</p>
<ul>
<li>所有设备代码中声明的自动变量(即不加额外前缀的变量)，通常都分配在寄存器上，但有些情况下有可能会将其放在局部内存中。</li>
</ul>
<h3 id="CUDA线程的总结"><a href="#CUDA线程的总结" class="headerlink" title="CUDA线程的总结"></a><code>CUDA</code>线程的总结</h3><ul>
<li>同一个线程格中的所有线程执行同一个核函数，也就是说一个线程格只能对应一个核函数</li>
<li>线程格可以以一维、二维、三维数组的方式组织线程块(gridDim.x, gridDim.y, gridDim.z)</li>
<li>每个线程块可以以一维、二维、三维的数组方式组织线程(blockDim.x, blockDim.y, and blockDim.z)</li>
<li>核函数一经调用，它的维数将无法再改变</li>
<li>同一个线程格中的所有线程块具有相同的维度</li>
<li>一个线程块中可以包含的最大线程总数为1024(不同的硬件不一定一样)。也就是说当使用多维线程块来组织线程时各维总乘积必须在这个每个线程块中最大线程总数之内，例如我的机器使用属性输出结果为“  Maximum number of threads per block:1024, Max dimension size of a thread block (x,y,z): (1024, 1024, 64)”，并不是说我可以定义的三维线程块<code>dim3 blocks(x, y, z);</code>中的<code>x,y,z</code>可以取的最大值分别为<code>1024, 1024, 64</code>，而是<code>x*y*z &lt;= 1024</code>。线程格如何有限制也是如此，只是线程格维度较大。(ps:当时这里我理解错了，检查一个下午无解，直到后来添加了错误处理才发现，所以一定要写上错误处理)</li>
<li>线程块一旦指派给某个流处理器(SM=streaming multiprocessor)，则该线程块中的所有线程必须全部在这个SM中执行。也就是说同一个线程块中的所有线程将在同一个SM中执行。</li>
<li>指派给SM的线程块中的线程以线程束(warp)的形式组织。线程束就是SM中的线程队列单元即SM的最小组成单元，线程束中的线程ID是连续递增的。一般一个线程束中只有32个线程。</li>
<li>线程束的执行速度与该线程束中执行最慢的线程一样，因为线程束中的所有线程“步调一致”地执行。</li>
<li>对于线程来说我们需要关注硬件限制的如下参数: <code>threads/SM</code>, <code>blocks/SM</code>, <code>threads/block</code>, <code>threads/warp</code></li>
<li>同一个SM中的线程共享资源，所以为了性能最大化，通常应该优化线程中的资源占用，以保证我们的SM中的线程全部可以启动（因为当前资源不够时，CUDA会以wrap为单位来减少每个SM中的线程启动数量）。我们可以同时并行执行的线程数量也就是SM的总数乘以每个SM中可以执行的最大线程数，当我们需要启动的总线程数超过这个数字时，CUDA实际上会将需要启动的block组成队列，以block为单位来调度执行这些线程。而我们的核函数定义中实际上可以启动的线程总数除了受官方CUDA定义中的限制之外，主要还是受到我们的核函数对资源占用的限制。</li>
</ul>
<p><strong>关于deviceQuery给出的数据</strong><br>下面是我当前显卡<code>GTX1080</code>的输出：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line">CUDA Device Query (Runtime API) version (CUDART static linking)</span><br><span class="line"></span><br><span class="line">Detected 1 CUDA Capable device(s)</span><br><span class="line"></span><br><span class="line">Device 0: &quot;GeForce GTX 1080&quot;</span><br><span class="line">  CUDA Driver Version / Runtime Version          9.1 / 9.0</span><br><span class="line">  CUDA Capability Major/Minor version number:    6.1</span><br><span class="line">  Total amount of global memory:                 8192 MBytes (8589934592 bytes)</span><br><span class="line">  (20) Multiprocessors, (128) CUDA Cores/MP:     2560 CUDA Cores</span><br><span class="line">  GPU Max Clock rate:                            1734 MHz (1.73 GHz)</span><br><span class="line">  Memory Clock rate:                             5005 Mhz</span><br><span class="line">  Memory Bus Width:                              256-bit</span><br><span class="line">  L2 Cache Size:                                 2097152 bytes</span><br><span class="line">  Maximum Texture Dimension Size (x,y,z)         1D=(131072), 2D=(131072, 65536), 3D=(16384, 16384, 16384)</span><br><span class="line">  Maximum Layered 1D Texture Size, (num) layers  1D=(32768), 2048 layers</span><br><span class="line">  Maximum Layered 2D Texture Size, (num) layers  2D=(32768, 32768), 2048 layers</span><br><span class="line">  Total amount of constant memory:               65536 bytes</span><br><span class="line">  Total amount of shared memory per block:       49152 bytes</span><br><span class="line">  Total number of registers available per block: 65536</span><br><span class="line">  Warp size:                                     32</span><br><span class="line">  Maximum number of threads per multiprocessor:  2048</span><br><span class="line">  Maximum number of threads per block:           1024</span><br><span class="line">  Max dimension size of a thread block (x,y,z): (1024, 1024, 64)</span><br><span class="line">  Max dimension size of a grid size    (x,y,z): (2147483647, 65535, 65535)</span><br><span class="line">  Maximum memory pitch:                          2147483647 bytes</span><br><span class="line">  Texture alignment:                             512 bytes</span><br><span class="line">  Concurrent copy and kernel execution:          Yes with 2 copy engine(s)</span><br><span class="line">  Run time limit on kernels:                     Yes</span><br><span class="line">  Integrated GPU sharing Host Memory:            No</span><br><span class="line">  Support host page-locked memory mapping:       Yes</span><br><span class="line">  Alignment requirement for Surfaces:            Yes</span><br><span class="line">  Device has ECC support:                        Disabled</span><br><span class="line">  CUDA Device Driver Mode (TCC or WDDM):         WDDM (Windows Display Driver Model)</span><br><span class="line">  Device supports Unified Addressing (UVA):      Yes</span><br><span class="line">  Supports Cooperative Kernel Launch:            No</span><br><span class="line">  Supports MultiDevice Co-op Kernel Launch:      No</span><br><span class="line">  Device PCI Domain ID / Bus ID / location ID:   0 / 1 / 0</span><br><span class="line">  Compute Mode:</span><br><span class="line">     &lt; Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) &gt;</span><br><span class="line"></span><br><span class="line">deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 9.1, CUDA Runtime Version = 9.0, NumDevs = 1</span><br></pre></td></tr></table></figure>

<p>上面的数据可以看到我的显卡上20个SM，每个SM最多可以有有2048个线程（Maximum number of threads per multiprocessor:  2048），那我的显卡一次最大可执行的并发线程数量即<code>20 * 2048 = 40960</code>，从上面的数据中也可以看出我的显卡每个SM中最多可以包含2048个线程，那么也就最少可以包含2个block，因为一个block最多可以有1024个线程，一个wrap是32个线程，那一个SM就可以有64个wrap。<br>欢迎参考这里<a target="_blank" rel="noopener" href="https://stackoverflow.com/questions/2392250/understanding-cuda-grid-dimensions-block-dimensions-and-threads-organization-s">Understanding CUDA grid dimensions, block dimensions and threads organization</a></p>
<h3 id="CUDA中函数声明与调用总结"><a href="#CUDA中函数声明与调用总结" class="headerlink" title="CUDA中函数声明与调用总结"></a><code>CUDA</code>中函数声明与调用总结</h3><table>
<thead>
<tr>
<th>声明方式</th>
<th>执行硬件</th>
<th>调用者</th>
</tr>
</thead>
<tbody><tr>
<td><code>__device__ type DeviceFunc()</code></td>
<td>device</td>
<td>device</td>
</tr>
<tr>
<td><code>__global__ void KernelFunc()</code></td>
<td>device</td>
<td>Host</td>
</tr>
<tr>
<td><code>__host__ type HostFunc()</code></td>
<td>Host</td>
<td>Host</td>
</tr>
</tbody></table>
<ul>
<li>核函数返回值必须是<code>void</code></li>
<li><code>__device__</code>和<code>__host__</code>可以同时使用，单独使用<code>__host__</code>与不使用任何前缀直接声明是一样的</li>
<li>在编译认为合适的情况下会默认将所有<code>__device__</code>函数编译为<code>inline</code>的内联函数，使用<code>__noinline__</code>可以提示编译器在可能的情况下不进行设备函数的内联化，但此时函数体必须与声明在同一个文件。使用<code>__forceinline__</code>能够强制编译器将函数内联化。  </li>
<li><code>__global__</code>声明的核函数可以增加两个额外的参数用于指定动态分配的共享内存大小和流<code>kernel&lt;&lt;&lt;&gt;&gt;&gt;(Dg, Db, Ns, S);</code>。其中<code>Dg</code>就是类型为<code>dim3</code>的线程格大小和维数，也就是启动<code>Dg.x * Dg.y * Dg.z</code>个线程块，注意你机器的限制；<code>Db</code>为<code>dim3</code>类型的线程块大小和维数，也就是每个线程块启动<code>Db.x * Db.y * Db.z</code>个线程，这个参数注意最后一维大小通常较小，例如我的机器是64。<code>Ns</code>是<code>size_t</code>类型，用于指定每个线程块除了静态分配的<code>shared-memory</code>之外动态分配的<code>shared-memory</code>大小,单位<code>byte</code>，这部分动态内存将用于任何使用<code>__shared__</code>声明的外部数组变量，也就是说可以在核函数内部使用<code>extern</code>关键字声明一个不指定大小的数组，然后在调用核函数时通过<code>Ns</code>参数指定大小，注意数组应该为一维，<code>Ns</code>不指定时默认为0；<code>S</code>类型为<code>cudaStream_t</code>，用于指定关联的流，不指定时默认值为0。</li>
</ul>
<h3 id="CUDA中所有需要同步的操作"><a href="#CUDA中所有需要同步的操作" class="headerlink" title="CUDA中所有需要同步的操作"></a><code>CUDA</code>中所有需要同步的操作</h3><ul>
<li><code>__syncthreads();</code> 无需指定参数，只能有核函数调用，对同一个块中的所有线程进行同步，确保所有线程在执行完该语句之前的所有语句之后才会一起开始执行下一条语句。特别是当使用<code>shared-memory</code>时，要使用一个同步来保证对共享内存的写操作都已经完成。<strong>注意要避免出现线程发散的情况</strong>。</li>
<li><code>cudaEventSynchronize(stop);</code> 指定需要同步的事件，由主机调用。用于CPU同步事件，确保在CPU执行该语句下一条语句之前所有对事件的操作都已经完成。<strong>该语句只能用于同步仅含有GPU代码的事件。</strong></li>
<li><code>cudaStreamSynchronize(&amp;stream)</code> 指定需要同步的流，由主机调用。用于对指定的流在CPU和GPU之间进行同步，以确保在CPU继续执行之前，GPU流队列中的所有操作都已经完成。</li>
<li><code>cudaDeviceSynchronize()</code>或者这个老函数<code>cudaThreadSynchronize();</code>(该函数官方文档提示不建议使用,未来会被前面的新函数取代)： 无需指定参数，由主机调用。用于调用核函数之后在GPU与CPU之间同步线程，阻塞当前CPU的执行，以确保CPU继续执行之前核函数所有需要处理的任务处理完毕。<strong>特别是在使用零拷贝内存是使用其确保GPU对主机内存的读写已经完成。</strong></li>
<li>所有的同步操作都是阻塞行为，由于GPU是异步执行，也就是说主机调用设备代码后就会立即开始继续执行自己的主机代码，所以需要这些阻塞行为。当不需要额外的同步操作时，额外的同步函数调用必然会降低一定的性能。而复制(<code>cudaMemcpy</code>)等没有明确提出需要进行同步的操作，<code>CUDA</code>都会有隐式同步。</li>
</ul>
<h3 id="关于性能"><a href="#关于性能" class="headerlink" title="关于性能"></a>关于性能</h3><ul>
<li>As we program GPUs we need to pay attention to several performance bottlenecks:<br>  – Branch diversion<br>  – Global memory latency<br>  – Global memory bandwidth<br>  – Limited resources</li>
<li>We have several techniques in our arsenal to enhance performance<br>  – Try to make threads in the same warp follow the same control flow<br>  – Tiling<br>  – Coalescing<br>  – Loop unrolling<br>  – Increase thread granularity<br>  – Trade one resource for another</li>
<li>Pay attention to interaction among techniques</li>
</ul>
<p><strong>首先学习下面的“线程块尺寸确定”文章中的分析，然后根据自己的问题，结合Nvidia Visual Profiler的分析对核函数进行调优</strong></p>
<h3 id="线程块尺寸的确定"><a href="#线程块尺寸的确定" class="headerlink" title="线程块尺寸的确定"></a>线程块尺寸的确定</h3><p>由于线程块尺寸对性能有着非常大的影响，同时还要受到Register、Shared-Memory的限制，所以单独分析在以下链接中<br><a href="http://notes.maxwi.com/2015/08/12/Determine-block-size/">Streaming MultiProcessor、Register、Shared-Memory对线程块尺寸的影响</a></p>
<h3 id="CUDA调试"><a href="#CUDA调试" class="headerlink" title="CUDA调试"></a>CUDA调试</h3><p>官方Nsight使用方法<br><strong>需要注意VS编译选项中要正确添加显卡CodeGeneration选项（对应于选项-arch=sm_62），例如GTX1080的为compute_62,sm_62;否则VS下使用Nsight无法命中断点，</strong></p>
<h3 id="CUDA中的几个重要宏"><a href="#CUDA中的几个重要宏" class="headerlink" title="CUDA中的几个重要宏"></a>CUDA中的几个重要宏</h3><p><code>__CUDACC__</code>：用于区分当前代码是否是由NVCC编译（#ifdef）、还是其他编译器，该宏如果未定义会导致cudaOccupancyMaxPotentialBlockSize等函数无法使用<br><code>__CUDA_ARCH__</code>：用于区分当前代码是在device侧编译（#ifdef）还是host侧编译</p>
<h3 id="常见问题"><a href="#常见问题" class="headerlink" title="常见问题"></a>常见问题</h3><ol>
<li>核函数无法启动。通常可以会因为是内存访问越界或者使用到了你的硬件不支持的属性。可以通过调试查看启动失败的原因。然后对照错误提示去官方<code>API</code>中搜索，或者这里<a target="_blank" rel="noopener" href="http://www.cs.cmu.edu/afs/cs/academic/class/15668-s11/www/cuda-doc/html/group__CUDART__TYPES_g3f51e3575c2178246db0a94a430e0038.html#g3f51e3575c2178246db0a94a430e0038">http://www.cs.cmu.edu/afs/cs/academic/class/15668-s11/www/cuda-doc/html/group__CUDART__TYPES_g3f51e3575c2178246db0a94a430e0038.html#g3f51e3575c2178246db0a94a430e0038</a></li>
</ol>

    </div>

    
    
    
        

  <div class="followme">
    <p>Welcome to my other publishing channels</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/CUDA/" rel="tag"># CUDA</a>
              <a href="/tags/Notes/" rel="tag"># Notes</a>
              <a href="/tags/Top/" rel="tag"># Top</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2015/05/03/Python-study-notes/" rel="prev" title="Python学习笔记">
      <i class="fa fa-chevron-left"></i> Python学习笔记
    </a></div>
      <div class="post-nav-item">
    <a href="/2015/06/22/cpp-study-notes/" rel="next" title="C++学习笔记之基础">
      C++学习笔记之基础 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="gitalk-container"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%B3%E4%BA%8E-%E5%87%86%E5%A4%87"><span class="nav-number">1.</span> <span class="nav-text">关于|准备</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#CUDA-C-%E7%AE%80%E4%BB%8B%E5%8F%8A%E5%9F%BA%E6%9C%AC%E6%A6%82%E5%BF%B5"><span class="nav-number">2.</span> <span class="nav-text">CUDA C++简介及基本概念</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#CUDA-C%E5%B9%B6%E8%A1%8C%E7%BC%96%E7%A8%8B%E7%9A%84%E4%B8%80%E7%BB%B4%E7%BA%BF%E7%A8%8B%E7%AE%A1%E7%90%86"><span class="nav-number">3.</span> <span class="nav-text">CUDA C并行编程的一维线程管理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BA%BF%E7%A8%8B%E5%8D%8F%E4%BD%9C-%E5%85%B1%E4%BA%AB%E5%86%85%E5%AD%98"><span class="nav-number">4.</span> <span class="nav-text">线程协作|共享内存</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B8%B8%E9%87%8F%E5%86%85%E5%AD%98-%E4%BA%8B%E4%BB%B6"><span class="nav-number">5.</span> <span class="nav-text">常量内存|事件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BA%B9%E7%90%86%E5%86%85%E5%AD%98%E5%92%8C%E8%A1%A8%E9%9D%A2-Texture-and-Surface-Memory"><span class="nav-number">6.</span> <span class="nav-text">纹理内存和表面(Texture and Surface Memory)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Texture-Memory"><span class="nav-number">6.1.</span> <span class="nav-text">Texture Memory</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Texture-Object-API"><span class="nav-number">6.1.1.</span> <span class="nav-text">Texture Object API</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Texture-Reference-API"><span class="nav-number">6.1.2.</span> <span class="nav-text">Texture Reference API</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Surface-Memory"><span class="nav-number">6.2.</span> <span class="nav-text">Surface Memory</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9B%BE%E5%BD%A2%E4%BA%92%E6%93%8D%E4%BD%9C%E6%80%A7"><span class="nav-number">7.</span> <span class="nav-text">图形互操作性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8E%9F%E5%AD%90%E6%80%A7"><span class="nav-number">8.</span> <span class="nav-text">原子性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%A1%B5%E9%94%81%E5%AE%9A%E4%B8%BB%E6%9C%BA%E5%86%85%E5%AD%98-CUDA%E6%B5%81"><span class="nav-number">9.</span> <span class="nav-text">页锁定主机内存|CUDA流</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%9B%B6%E6%8B%B7%E8%B4%9D%E5%86%85%E5%AD%98-%E5%8F%AF%E7%A7%BB%E5%8A%A8%E7%9A%84%E5%9B%BA%E5%AE%9A%E5%86%85%E5%AD%98"><span class="nav-number">10.</span> <span class="nav-text">零拷贝内存|可移动的固定内存</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%A4%9AGPU%E7%B3%BB%E7%BB%9F%E4%B8%8A%E7%9A%84CUDA-C"><span class="nav-number">11.</span> <span class="nav-text">多GPU系统上的CUDA C</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%BB%E7%BB%93%E4%B8%8E%E8%A1%A5%E5%85%85"><span class="nav-number">12.</span> <span class="nav-text">总结与补充</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#CUDA%E7%9A%84%E6%89%80%E6%9C%89%E5%86%85%E5%AD%98%E6%80%BB%E7%BB%93"><span class="nav-number">12.1.</span> <span class="nav-text">CUDA的所有内存总结</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#CUDA%E4%B8%AD%E5%8F%98%E9%87%8F%E5%A3%B0%E6%98%8E%E6%80%BB%E7%BB%93"><span class="nav-number">12.2.</span> <span class="nav-text">CUDA中变量声明总结</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#CUDA%E7%BA%BF%E7%A8%8B%E7%9A%84%E6%80%BB%E7%BB%93"><span class="nav-number">12.3.</span> <span class="nav-text">CUDA线程的总结</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#CUDA%E4%B8%AD%E5%87%BD%E6%95%B0%E5%A3%B0%E6%98%8E%E4%B8%8E%E8%B0%83%E7%94%A8%E6%80%BB%E7%BB%93"><span class="nav-number">12.4.</span> <span class="nav-text">CUDA中函数声明与调用总结</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#CUDA%E4%B8%AD%E6%89%80%E6%9C%89%E9%9C%80%E8%A6%81%E5%90%8C%E6%AD%A5%E7%9A%84%E6%93%8D%E4%BD%9C"><span class="nav-number">12.5.</span> <span class="nav-text">CUDA中所有需要同步的操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%85%B3%E4%BA%8E%E6%80%A7%E8%83%BD"><span class="nav-number">12.6.</span> <span class="nav-text">关于性能</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%BA%BF%E7%A8%8B%E5%9D%97%E5%B0%BA%E5%AF%B8%E7%9A%84%E7%A1%AE%E5%AE%9A"><span class="nav-number">12.7.</span> <span class="nav-text">线程块尺寸的确定</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#CUDA%E8%B0%83%E8%AF%95"><span class="nav-number">12.8.</span> <span class="nav-text">CUDA调试</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#CUDA%E4%B8%AD%E7%9A%84%E5%87%A0%E4%B8%AA%E9%87%8D%E8%A6%81%E5%AE%8F"><span class="nav-number">12.9.</span> <span class="nav-text">CUDA中的几个重要宏</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98"><span class="nav-number">12.10.</span> <span class="nav-text">常见问题</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="blueyi"
      src="/images/default_avatar.jpg">
  <p class="site-author-name" itemprop="name">blueyi</p>
  <div class="site-description" itemprop="description">心怀善意，虛怀若谷！</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">104</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">26</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">68</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/blueyi" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;blueyi" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="http://maxwi.com/" title="http:&#x2F;&#x2F;maxwi.com" rel="noopener" target="_blank">Maxwi</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2014 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">blueyi</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="Symbols count total">750k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="Reading time total">11:22</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://mist.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a>
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/pjax/pjax.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>

<script src="/js/utils.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>

<script src="/js/bookmark.js"></script>

  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '.languages',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[data-pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.dataset.pjax !== undefined) {
      script.dataset.pjax = '';
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>




  
  <script data-pjax>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













    <div id="pjax">
  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
NexT.utils.loadComments(document.querySelector('#gitalk-container'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : '0f8243eb2c8b2207980f',
      clientSecret: 'd159633a33519d3b7a48b0ca729032f7d1f38a41',
      repo        : 'notes',
      owner       : 'blueyi',
      admin       : ['blueyi'],
      id          : '2ca9aa575370997c4da6d4d13e03d959',
        language: '',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>

    </div>
</body>
</html>
